How to get GET parameters with ASP.NET MVC ApiController

后端 未结 8 1352
挽巷
挽巷 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:24

    You could just use

    HttpContext.Current.Request.QueryString
    
    0 讨论(0)
  • 2021-01-07 17:25

    Adding a default value does the job:

    public string Get(string sort="")
    
    0 讨论(0)
  • 2021-01-07 17:26

    You can also use the following

    var value = request.GetQueryNameValuePairs().Where(m => m.Key == "paramName").SingleOrDefault().Value;
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-07 17:27

    Get all querystring name/value pairs into a variable:

    IEnumerable<KeyValuePair<string, string>> queryString = request.GetQueryNameValuePairs();
    

    Then extract a specified querystring parameter

    string value = queryString.Where(nv => nv.Key == "parameterNameGoesHere").Select(nv => nv.Value).FirstOrDefault();
    
    0 讨论(0)
  • 2021-01-07 17:27

    if we have a proper model for that request

    for example

      public class JustModel 
        {
          public int Id {get;set;}
          public int Age {gets;set;}
        }
    

    and query like this

    /api/foo?id=1&Age=10
    

    You could just use [FromUri] attribute

    For example

    public IHttpActionResult GetAge([FromUri] JustModel model){}
    
    0 讨论(0)
提交回复
热议问题