简体   繁体   中英

How to get GET parameters with ASP.NET MVC ApiController

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 ApiController class, I gave a public string Get() . Putting Get(string sort) makes /api/foo a bad request. Request instance in the ApiController is of type System.Net.Http.HttpRequestMessage . It doesn't have a QueryString or Parameters property or anything.

The ApiController is designed to work without the HttpContext object (making it portable, and allowing it to be hosted outside of IIS).

You can still access the query string parameters, but it is done through the following property:

Request.GetQueryNameValuePairs()

Here's an example loop through all the values:

foreach (var parameter in Request.GetQueryNameValuePairs())
{
     var key = parameter.Key;
     var value = parameter.Value;
}

你可以用

HttpContext.Current.Request.QueryString

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

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();

您还可以使用以下

var value = request.GetQueryNameValuePairs().Where(m => m.Key == "paramName").SingleOrDefault().Value;

You're trying to build an OData webservice? If so, just return an IQueryable, and the Web API will do the rest.

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){}

添加默认值可以完成以下工作:

public string Get(string sort="")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM