Notes On <Practical ASP.NET Web API> - 01

来源:互联网 发布:网络前沿技术有哪些 编辑:程序博客网 时间:2024/06/05 18:27



Chp-1: Building a Basic Web API


Highlights:

  1. The default convention is to give the action method the same name as the HTTP method or to name the method so that it starts with the HTTP method.And the default behavior of the ASP.NET Web API framework in selecting the action method of the controller is based on the HTTP method.
  2. [HttpGet] attribute is short for [AcceptVerbs("GET")] attribute.
  3. To select an action method based on the action method specified in the URI is called RPC style, which is the same way that ASP.NET MVC selects action methods.
  4. If you need to make an new entry in the WebApiConfig.cs file under App_Start folder, make sure it is added before the existing MapHttpRoute.
  5. You can change the literal segment in your route template, and add placeholder variable into it, which supports regular expression.
    config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{orgid}/{controller}/{id}",defaults: new { id = RouteParameter.Optional },constraints: new { orgid = @"\d+" });
  6. Playing by the Rules of HTTPRetrieving resourcesThe HTTP GET method should be used.GET
    • Retrieving a resource that does not match any ID should get 404 "Not Found" status code.
    • When retrieving a list of resources matching the query parameter, and the parameter in the request is not a valid one, 422 "Unprocessable Entity" status code is returned. 400 "Bad Request" status code is accepted as well.
     Creating resourcesWith server generated idPOST
    • In the case of resource creation using POST, returning the HTTP status code of 201 - Created and the URI of the new resource created in the location response header will be better.
    • POSTing with an ID, which doesn't exist, must be rejected with a 404 - Not Found.
     With a client supplied idPUT
    • Return the HTTP status code of 201 - Created and with the URI of the new resource created in the location response header.
    • If the provided ID exists already, return the HTTP status code of 204 - No Content.
     Updating resourceOverwriting a resourcePUT
    • The resource must be updated entirely, and the id must exist. Partial updates are not allowed.
    • If the ID exists, overwrite it, return the HTTP status code of 204 - No Content.
    • Otherwise, create a new resource with the ID, return the HTTP status code of 201 - Created, and with the URI of the new resource in the location header.
     Entirely updating a resourcePOST
    • If the ID doesn't exist, return the HTTP status code of 404 - Not Found.
    • Otherwise, update the resource entirely, return 204 - No Content.
     Partilly updaing a resourcePATCH  Deleting resource DELETE
    • In case that the resourse is deleted physcially or doesn't exist, always return 204.
    • If the resource is deleted softly on the server side, then return 202 - Accepted.
     
  7. [FromURI]Filter keyword
  8. Delta<T>



Chp-3: Media-Type Formatting CLR Objects

From the ASP.NET Web API perspective, serialization is the process of translating a .NET Common Language Runtime(CLR) type into a format that can be transmitted over HTTP. The format is either JSON or XML, out of the box.
The MediaTypeFormatter object in the ASP.NET Web API pipeline performs this serialization. It serializes the object returned by the action method into JSON or XML, which is then written into the response message body. The out-of-box media formatters that produce JSON and XML are respectively JsonMediaTypeFormatter and XmlMediaTypeFormatter, both deriving from MediaTypeFormatter. The process through which the MediaTypeFormatter is chosen is called content negotiation, commonly shortened to conneg.


How does Conneg decide to use which media type formatter to perform the serialization:


  • The value of X-Media field in header of request
    But you need to add some lines to the Register method in WebApiConfig in the App_Start folder:
    using System;using System.Diagnostics;using System.Web.Http;using HelloWebApi.Models;public static class WebApiConfig{public static void Register(HttpConfiguration config){// ...config.Formatters.JsonFormatter.MediaTypeMappings.Add(new RequestHeaderMapping("X-Media", "json",StringComparison.OrdinalIgnoreCase, false,new MediaTypeHeaderValue("application/json")));}}
  • Query string
    You still need to add lines to achieve that function:
    using System;using System.Diagnostics;using System.Web.Http;using HelloWebApi.Models;public static class WebApiConfig{public static void Register(HttpConfiguration config){// ...config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("frmt", "json",new MediaTypeHeaderValue("application/json")));config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("frmt", "xml",new MediaTypeHeaderValue("application/xml")));}}
    And now with that query string in place, you can try this out in your browser: http://localhost:55778/api/employees/12345?frmt=json
  • Accept field in header of request
    Just specify Accept: application/json or Accept: application/xml in request headers. You can specify a quality value indicating the relative preference. The range is 0–1, with 0 being unacceptable and 1 being the most preferred. The default value is 1. For example, if you send the request header Accept: application/json; q=0.8, application/xml;q=0.9, the response message will be XML, because application/xml has a quality value of 0.9, which is higher than the quality value of 0.8 specified for application/json.
  • Content type field in header of request
    Just specify Content-Type: application/json or Content-Type: application/xml in request headers.
  • The first format that can serialize the type in MediaTypeFormatter objects defined in the config.
    You can list them by adding lines:
    using System;using System.Diagnostics;using System.Web.Http;using HelloWebApi.Models;public static class WebApiConfig{public static void Register(HttpConfiguration config){// ...foreach (var formatter in config.Formatters){Trace.WriteLine(formatter.GetType().Name);Trace.WriteLine("\tCanReadType: " + formatter.CanReadType(typeof(Employee)));Trace.WriteLine("\tCanWriteType: " + formatter.CanWriteType(typeof(Employee)));Trace.WriteLine("\tBase: " + formatter.GetType().BaseType.Name);Trace.WriteLine("\tMedia Types: " + String.Join(", ", formatter.SupportedMediaTypes));}}}
    You would see something like:
    // OutputJsonMediaTypeFormatterCanReadType: TrueCanWriteType: TrueBase: MediaTypeFormatterMedia Types: application/json, text/jsonXmlMediaTypeFormatterCanReadType: TrueCanWriteType: TrueBase: MediaTypeFormatterMedia Types: application/xml, text/xmlFormUrlEncodedMediaTypeFormatterCanReadType: FalseCanWriteType: FalseBase: MediaTypeFormatterMedia Types: application/x-www-form-urlencodedJQueryMvcFormUrlEncodedFormatterCanReadType: TrueCanWriteType: FalseBase: FormUrlEncodedMediaTypeFormatterMedia Types: application/x-www-form-urlencoded








0 0