Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

routing - Accessing the query string in ASP.Net Web Api?

I'm using the default template generated by Asp.net Web Api. I'm working with the Get() Part:

        // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

For some reason the i thought the only thing you had to do to access to query string was just to create an input string variable. So i created one more function (the only change i made) to the default controller generated:

        public IEnumerable<string> Get(string queryString)
    {
        return new string[] { "value3", "value4" };
    }

I put a break point in both methods but even if i add a query string it always goes to the function with no parameters. So if i go to http://mybaseurl/api/values?foo=f it still is going to Get() instead of get(string queryString). Does it not work the way i thought? I know i can access the query string in the Get() function using Request.RequestUri.ParseQueryString(); but i prefer to have it separated like this if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Even though @Kiran Challa's answer is correct, there are few situations that you might prefer to get URL parameters directly from the URL. in those scenarios, try this:

using System.Net.Http;

var allUrlKeyValues = ControllerContext.Request.GetQueryNameValuePairs();

string p1Val = allUrlKeyValues.LastOrDefault(x => x.Key == "p1").Value;
string p2Val = allUrlKeyValues.LastOrDefault(x => x.Key == "p2").Value;
string p3Val = allUrlKeyValues.LastOrDefault(x => x.Key == "p3").Value;

Now for the following URL, p1Val will be "Apple", p2Val will be "Banana", and p3Val will be null.

.../api/myController?p1=Apple&p2=Banana

Update:

Thanks for the suggestions, now, the source code for this test is in GitHub and it also runs and can be tested on Azure:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...