Content negotiation is the process of selecting the best representation for given content Response when multiple representations are available. means, depends on The header value in the request is accepted and the server sends the response. first The mechanism for content negotiation in HTTP is these request headers -
Accept - which media types are acceptable for the response, such as "application/json", "application/xml" or a custom media type , e.g. "application/vnd.example xml"
Accept-Charset - Which character sets are acceptable, e.g. UTF-8 or ISO 8859-1 .
Accept-Encoding - Which content encodings are acceptable, such as gzip.
Accept-Language - Prefer natural encoding languages, such as "en-us".
The server can also look at other parts of the HTTP request. For example, if The request contains the X-Requested-With header, indicating an AJAX request, and the server If there is no Accept header, it may default to JSON.
In content negotiation, the pipeline starts from HttpConfiguration object. It also gets the list of media formatters from HttpConfiguration.Formatters collection.
Next, the pipeline calls IContentNegotiator.Negotiate, passing in -
The Negotiate method returns two pieces of information -
If the formatter is not found, the Negotiate method returns null and the client receives HTTP Error 406 (Unacceptable).
Let us consider the following StudentController.
using DemoWebApplication.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace DemoWebApplication.Controllers{ public class StudentController : ApiController{ List<Student> students = new List<Student>{ new Student{ Id = 1, Name = "Mark" }, new Student{ Id = 2, Name = "John" } }; } }
One of the standards for a RESTful service is that the client should be able to Decide which format of response they want - XML, JSON, etc. Sent to the server containing the Accept header. Using the Accept header, the client can Specify the format of the response. For example
Accept: application/xml returns XML Accept: application/json returns JSON
The output below shows that when we pass the Accept header as XML, the response is XML Application/XML.
The output below shows that when we pass the Accept header as JSON, the response is JSON application/JSON.
When the response is sent to the client in the requested format, please note that The response's Content-Type header is set to the appropriate value. For example, if The client requests application/xml, and the server sends data in XML format. Also set Content-Type=application/xml.
We can also specify the figure of merit. In the example below, xml has higher quality Factor is more important than json, so the server uses an XML formatter and formats the data into XML. application/xml;q=0.8,application/json;q=0.5
The above is the detailed content of What is content negotiation in Asp.Net webAPI C#?. For more information, please follow other related articles on the PHP Chinese website!