A summary of the ASP. NET Web API querystring Access

Source: Internet
Author: User

Since I started using the ASP. All kinds of routes have been bothering me with the egg-ache problem, I believe everyone is the same.

The routing configuration of the Web API is similar to ASP.MVC, where there is a Webapiconfig class file  config under the App_start folder. Routes.maphttproute (    Name: "Defaultapi",    routetemplate: "Api/{controller}/{id}",    Defaults:new {id = routeparameter.optional}), the above is a routing configuration for an empty Web API project.   We create a new Controller public class testroutecontroller:apicontroller{    public httpresponsemessage GetUser (int id)     {        return Request.createresponse (Httpstatuscode.ok, new  & nbsp     {            status = "Success",            data = new {id = id, Name = "user" + ID}       });   }} as described in MSDN  to find the action, Web A PI looks at the HTTP method, and then looks for a action whose name begins with that HTTP method name. For example, with a GET request, the Web API looks for a action, the starts with "GET ...", such as "getcontact" or "Getallcon Tacts ". This Convention Applies only to GET, POST, PUT, and DELETE methods. You can enable the other HTTP methods by using the attributes on your controller. We'll see a example of that Later. web API convention, if the method name has get, then it is a GET request, other requests in the same way, of course, we can also use features such as HttpGet, HttpPost, or Acceptverbs ("GET", "POST",...) And so on, to control the way we request it.   According to the routing configuration, we can understand that our access address should be: api/testroute/123, the request is get   no doubt, we got the desired result: {"status": "Success", "data": {"Id ": 123," Name ":" User 123 "}}  according to our previous MVC route understanding, the route, new {id = routeparameter.optional} indicates that the ID parameter is an optional parameter, which we expect, in case No ID is passed in, The address can be accessed normally and the ID is the default value of 0.   Unfortunately, it's 404 straight.   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 the method parameter ID to a default value, incredibly successful    we will change another access mode, api/testroute/?id=123 in the case of parameters can be normal access. While accessing api/testroute/?id=, {"Message" appears: "The request is invalid. "," Messagedetail ":" For "WebApiTest.Controllers.TestRouTecontroller "Method" System.Net.Http.HttpResponseMessage GetUser (System.DateTime) "parameter of the non-nullable type" System.DateTime " Time ", the parameter dictionary contains a null entry. An optional parameter must be a reference type, a nullable type, or a declaration as an optional parameter. "} 400 error. Set the ID parameter to int? type, and we access http://localhost:62488/api/TestRoute/?id= to access it normally, and the ID is null at this time.   After the above tests, we can conclude that:  in the ASP. NET Web API, and we know that C # int is unassigned when the default 0,bool is not assigned, the default false is not applicable here if the requested parameter is defined on the method, The parameter name must be spliced at the access address   Let's try another case, we'll need to put the incoming parameter into a class and pass it directly to the 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 = queryparams.id, Name = "User:" + queryparams.name}   });         direct access to api/testroute/, we will find that regardless of whether we pass in parameters, our parameter objects are null.    this time we need to add a Fromuri feature to our parameter object to tell the Web API that the properties of our object are all fromURL link uploaded   this time still does not pass any parameters, but surprised to find that our object parameters are no longer null, where the value of the property is also consistent with our expectation (C # int is not assigned default 0,string default null)    After this further attempt, we can refine our conclusion   when stitching parameters by QueryString method   If the requested parameter is a type defined by C # syntax and is defined on the method, the parameter name must be stitched at the access address if the requested parameter is an entity class, You need to add [Fromuri] attributes for this parameter.

ASP. NET Web API QueryString Access Summary

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.