Summary of ASP. NET Web API queryString access, apiquerystring

Source: Internet
Author: User

Summary of ASP. NET Web API queryString access, apiquerystring

Since I started using ASP. NET Web APIs, the problem of various routes has been bothering me, and I believe everyone is the same.

Web API routing configuration and ASP. similar to MVC. In the App_Start folder, there is a WebApiConfig file config. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional}); the preceding is the routing configuration of an empty Web API project. Create a new Controller public class TestRouteController: ApiController {public HttpResponseMessage GetUser (int id) {return Request. createResponse (HttpStatusCode. OK, new {status = "success", data = new {Id = id, Name = "user" + id}) ;}follow the msdn instructions To find the action, web API looks at the HTTP method, and then looks for an action whose name begins with that HTTP method name. for example, with a GET requ Est, Web API looks for an action that starts with "Get... ", such as" GetContact "or" GetAllContacts ". this convention applies only to GET, POST, PUT, and DELETE methods. you can enable other HTTP methods by using attributes on your controller. we'll see an example of that later. the Web API stipulates that if the method name has Get, it is a Get request. For other request methods, we can also use features such as HttpGet and HttpPost, or AcceptVerbs ("GET ", "POST ",...) and so on. According to the route configuration, we can understand that our access address should be: api/TestRoute/123, and the request method is GET without any doubt. We GET the expected result: {"status ": "success", "data": {"Id": 123, "Name": "User 123"} according to our previous understanding of MVC routing, new {id = RouteParameter. optional} indicates that the id parameter is an Optional parameter. We expect that the address can be accessed normally without an id. The default value is 0. Unfortunately, it's 404. Let's simply change the code public HttpResponseMessage GetUser (int id = 0) {return Request. createResponse (HttpStatusCode. OK, new {status = "success", data = new {Id = id, Name = "user" + id}) ;}we set a default value for the method parameter id, actually, we changed the access method to api/TestRoute /? Id = 123 can be accessed normally when there is a parameter. And access api/TestRoute /? {"Message": "The request is invalid. "," MessageDetail ":" for "WebApiTest. controllers. in TestRouteController, the method "System. net. http. httpResponseMessage GetUser (System. dateTime) "cannot be null type" System. dateTime. The parameter dictionary contains a null item. Optional parameters must be of the reference type, can be null, or declared as optional parameters. "} Error 400. Set the id parameter to int? Type. http://localhost:62488/api/TestRoute/?id= The access is normal, and the id is null. After the above tests, can we draw a conclusion: In ASP. NET Web API, and the well-known C # int Is not assigned a value, the default value is 0, and the default value is false when bool is not assigned a value. This is not applicable here. If the request parameter is defined on the method, then the parameter name must be spliced on the access address. Let's try again. We will put the parameters to be passed in to a class, directly pass in this parameter object public class QueryParams {public int Id {get; set;} public string Name {get; set ;}} public HttpResponseMessage GetUser (QueryParams queryParams) {return Request. createResponse (HttpStatusCode. OK, new {status = "success", data = new {Id = query Params. id, Name = "User:" + queryParams. name});} directly access api/TestRoute/. We will find that our parameter object is null no matter whether we pass in the parameter or not. At this time, we need to add a FromUri feature to our parameter object to tell the web api that the attributes of this object are uploaded from the url link, and no parameters are input at this time, we were surprised to find that our object parameter is no longer null, and the attribute value is the same as we expected (0 by default when C # int Is not assigned a value, and null by string) after this further attempt, we can improve our conclusion that when the queryString method is used to concatenate a parameter, if the request parameter is of the type defined in the C # syntax and is defined in the method, the parameter name must be spliced on the access address. If the request parameter is an object class, you must add the [FromUri] feature for this parameter.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.