How to get GET parameters with ASP.NET MVC ApiController

后端 未结 8 1417
挽巷
挽巷 2021-01-07 16:54

I feel a bit absurd asking this but I can\'t find a way to get parameters for a get request at /api/foo?sort=name for instance.

In the ApiControll

8条回答
  •  庸人自扰
    2021-01-07 17:27

    Here's an example that gets the querystring q from the request and uses it to query accounts:

            var q = Request.GetQueryNameValuePairs().Where(nv => nv.Key =="q").Select(nv => nv.Value).FirstOrDefault();
            if (q != null && q != string.Empty)
            {
                var result = accounts.Where(a=>a.Name.ToLower().StartsWith(q.ToLower()));
                return result;
            }
            else
            {
                throw new Exception("Please specify a search query");
            }
    

    This can be called then like this:

    url/api/Accounts?q=p

提交回复
热议问题