[ASP. NET web API tutorial] 6.3 content negotiation

Source: Internet
Author: User

This is section 6.3 of the web API series.

6.3 content negotiation
6.3 content negotiation

From: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation

By Mike Wasson | May 20,201 2
Author: Mike Wasson | Date:

This article describes how ASP. NET web API implements content negotiation.
This article describes how ASP. NET Web APIs implement content negotiation.

The HTTP specification (RFC 2616) defines content negotiation as "the process of selecting the best representation for a given response when there are multiple representations available. "The primary mechanic for content negotiation in HTTP are these request headers:
The HTTP specification (RFC 2616) defines content negotiation as "selecting the best performance process for a given response when multiple representations are available ". The main mechanism of content negotiation in HTTP is the following request header:

    • Accept : Which media types are acceptable for the response, such as "application/JSON," "application/XML, "Or a custom media type such as" application/vnd. example + XML "
      Accept: types of media that can be received in response, such as" application/JSON "and" application/XML ", or customize the media type, such as "application/vnd. example + XML ".
    • Accept-charset : Which character sets are acceptable, such as UTF-8 or ISO 8859-1.
      Accept-charset: an acceptable character set, for example, UTF-8 or ISO 8859-1 ".
    • Accept-encoding : Which content encodings are acceptable, such as gzip.
      Accept-encoding: the acceptable content encoding, such as "gzip ".
    • Accept-language : the preferred natural language, such as "En-us ".
      Accept-language: the preferred natural language, such as "En-us ".

The server can also look at other portions of the HTTP request. for example, if the request contains an X-requested-with header, indicating an Ajax request, the server might default to JSON if there is no accept header.
The server can also view other options of the HTTP request. For example, if the request contains an X-requested-with header, it indicates that this is an Ajax request. If there is no accept header, the server may use JSON by default.

In this article, we'll look at how web API uses the accept and accept-charset headers. (at this time, there is no built-in support for accept-encoding or accept-language .)
This article describes how to use the accept and accept-charset headers for Web APIs. (Currently, there is no built-in support for accept-encoding or accept-language .)

6.3.1 serialization
6.3.1 serialization

If a web API controller returns a resource as CLR type, the pipeline serializes the return value and writes it into the HTTP response body.
If the web API controller returns a CLR-type response, the (request processing) pipeline serializes the returned value and writes it to the HTTP response body.

For example, consider the following controller action:
For example, consider the following controller actions:

 
Public Product getproduct (int id) {var item = _ products. firstordefault (P => P. id = ID); If (item = NULL) {Throw new httpresponseexception (httpstatuscode. notfound);} return item ;}

A client might send this HTTP request:
The client may send such an HTTP request:

 
Get http: // localhost.: 21069/API/products/1 HTTP/1.1 HOST: localhost.: 21069 accept: Application/JSON, text/JavaScript, */*; q = 0.01

In response, the server might send:
The server may send the following response:

 
HTTP/1.1 200 okcontent-type: Application/JSON; charset = utf-8Content-Length: 57 connection: Close
{"ID": 1, "name": "Gizmo", "category": "widgets", "price": 1.99}

In this example, the client requested either JSON, JavaScript, or "anything "(*/*). the server responsed with a JSON representation of the product object. notice that the Content-Type header in the response is set to "application/JSON ".
In this example, the client request (specified) contains JSON, JavaScript, or "any format (*/*)". The server responds with a JSON representation of a product object. Note that the Content-Type header in the response has been set to "application/JSON ".

A controller can also return an httpresponsemessage object. to specify a CLR object for the response body, call the createresponse extension method:
The controller can also return an httpresponsemessage object. To specify the CLR object of the response body, call the createresponse Extension Method (note:CodeIs an Action Method in the controller, not the entire controller. Note ):

 
Public httpresponsemessage getproduct (int id) {var item = _ products. firstordefault (P => P. id = ID); If (item = NULL) {Throw new httpresponseexception (httpstatuscode. notfound);} return request. createresponse (httpstatuscode. OK, product );}

This option gives you more control over the details of the response. You can set the status code, add HTTP headers, and so forth.
This option gives you more control over the Response Details. You can set status codes and add HTTP headers.

The object that serializes the resource is calledMedia formatter. Media formatters derive fromMediatypeformatterClass. web API provides media formatters for XML and JSON, And you can create custom formatters to support other media types. For information about writing a custom formatter, see media formatters.
The object for resource serialization is calledMedia formatter(Media formatter ). The media formatter is derived fromMediatypeformatterClass. Web APIs provide XML and JSON media formatters. Therefore, you can create custom formatters to support other media types. For more information about writing a custom formatter, see "Media formatter (section 6.1-Translator's note in this series of tutorials )".

6.3.2 how content negotiation works
6.3.2 Working Mechanism of content negotiation

First, the pipeline getsIcontentnegotiatorService fromHttpconfigurationObject. It also gets the list of media formatters fromHttpconfiguration. formattersCollection.
First, the pipeline will obtainHttpconfigurationObjectIcontentnegotiatorService. It will also getHttpconfiguration. formattersList of media Referer sets.

Next, the pipeline CILSIcontentnegotiatior. Negotiate, Passing in:
Next, the pipeline will callIcontentnegotiatior. Negotiate, And pass in:

    • The type of object to serialize
      Object type to be serialized
    • The collection of media formatters
      Media formatter set
    • The HTTP Request
      HTTP Request

TheNegotiateMethod returns two pieces of information:
NegotiateThe method returns two pieces of information:

    • Which formatter to use
      Formatter to be used
    • The media type for the response
      Media type used for response

If no formatter is found,NegotiateMethod returnsNull, And the client recevies HTTP Error 406 (not acceptable ).
If the formatter is not found, the method returnsNullThe client will receive an HTTP 406 (unacceptable) error.

The following code shows how a controller can directly invoke content negotiation:
The following code shows how the controller can directly call content negotiation:

Public httpresponsemessage getproduct (int id) {var Product = new product () {id = ID, name = "Gizmo", Category = "widgets", price = 1.99 m };
Icontentnegotiator negotiator = This. configuration. Services. getcontentnegotiator ();
Contentnegotiationresult result = negotiator. negotiate (typeof (product), this. request, this. configuration. formatters); If (result = NULL) {var response = new httpresponsemessage (httpstatuscode. notacceptable); throw new httpresponseexception (response ));}
Return new httpresponsemessage () {content = new objectcontent <product> (product, // What we are serializing (what to serialize) result. formatter, // The media formatter (Media formatter result. mediatype. mediatype // The MIME type (MIME type ))};}

This code is equivalent to the what the pipeline does automatically.
The above code is equivalent to Automatic completion of pipelines.

6.3.3 default content negotiator
6.3.3 default content calculator

TheDefaultcontentnegotiatorClass provides the default ImplementationIcontentnegotiator. It uses several criteria to select a formatter.
DefaultcontentnegotiatorClass providesIcontentnegotiator. It uses several conditions for selecting the formatter.

First, the formatter must be able to serialize the type. This is verified by callingMediatypeformatter. canwritetype.
First, the formatter must be able to serialize the type.Mediatypeformatter. canwritetype.

Next, the content negotiator looks at each formatter and evaluates how well it matches the HTTP request. To evaluate the match, the content negotiator looks at two things on the formatter:
Secondly, the content calculator should examine each formatter and evaluate whether the formatter matches the HTTP request. In order to evaluate the matching condition, the content calculator should examine two things of the formatter:

    • the supportedmediatypes collection, which contains a list of supported media types. the content negotiator tries to match this list against the request accept header. note that the accept header can include ranges. for example, "text/plain" is a match for text/* or */*.
      supportedmediatypes set, which contains a list of supported media types. The content validator tries to match the list based on the request's accept header. Note that the accept header can include a range. For example, "text/plain" can match "text/*" or "*/*"
    • the mediatypemappings collection, which contains a list of mediatypemapping objects. the mediatypemapping class provides a generic way to match HTTP requests with media types. for example, it cocould map a custom HTTP header to a special media type.
      mediatypemappings set, which contains a list of mediatypemapping objects. The mediatypemapping class provides a generic method to match HTTP requests with media types. For example, it can map a custom HTTP header to a specific media type.

If there are multiple matches, the match with the highest quality factor wins. For example:
If multiple matches exist, match with the highest quality factor wins. For example:

 
Accept: Application/JSON, application/XML; q = 0.9, */*; q = 0.1

In this example, application/JSON has an implied quality factor of 1.0, so it is preferred over application/XML.
In this example, application/JSON has an implicit quality factor of 1.0, so it is better than application/XML.

If no matches are found, the content negotiator tries to match on the media type of the Request body, if any. for example, if the request contains JSON data, the content negotiator looks for a JSON formatter.
If no match is found, the content validator attempts to match the media type of the Request body (when a request body exists ). For example, if the request contains JSON data, the content calculator will find the JSON formatter.

If there are still no matches, the content negotiator simply picks the first formatter that can serialize the type.
If no match exists, the content validator simply retrieves the first formatter that can serialize the type.

6.3.4 selecting a character encoding
6.3.4 select character encoding

After a formatter is selected, the content negotiator chooses the best character encoding. by looking atSupportedencodingsProperty on the formatter, and matching it against the accept-charset header in the request (if any ).
After the formatter is selected, the content calculator selects the best character encoding. Evaluate the knowledgeSupportedencodingsAnd match (if any) according to the request submission ).

After reading this article, please giveRecommendation.
Your recommendation is the motivation for me to continue, and it will attract more people to pay attention to and benefit from it. This is also your contribution.

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.