Accessing the query string in ASP.Net Web Api?

﹥>﹥吖頭↗ 提交于 2019-11-28 20:06:09
Kiran Challa

The query string key name should match the parameter name of the action:

/api/values?queryString=f

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

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!