Use ASP.NET Core 3.x build RESTful API - 3.4 Content Negotiation

Now, when talking about  RESTful Web API  time, people always think of  JSON . But in fact, JSON  and  RESTful API  is not half dime, but  JSON  is exactly RESTful API  presentation format of results. That  RESTful API  may also use other expression formats, e.g.  xml  or proprietary format. This means that we need to make  RESTful API  to know the format that we want to return. And that's HTTP one of the core content of the request and response: 

 

Content Negotiation Content negotiation  

Content negotiation is the process: for a response when expressed in a variety of formats available, select the best of a statement. 

 

When our RESTful API only for a API consumers, perhaps only use  JSON  format is no problem. But if you need more face various forms of API consumers, it is likely that a small number of API consumers can not resolve a good JSON , they may be more accustomed to xml or other formats. 

 

So how to solve this problem? 

HTTP request  Accept Header is used to solve this problem, API consumers when sending the request, in the Accept Header  inside fill  Media Type (Media type), such as  the Application / json  or  the Application / xml and so on.  

If the request is to fill in  the Application / J Son , then RESTful API returns a response representation format should be the  json ... 

 

And if the request does not fill in the Accept Header , then  RESTful API  had to use its default format of the response.  

If  Accept Header  which fill the format is not  RESTful API  supported, it touches can also return to the default format, but still want to try to avoid this situation, in fact, the best way for this situation is to return  406 ( Not Acceptable ) status code indicates  API media type of consumer requests is unacceptable, as it can not be in the format of the response.  

 

In summary, the Accept Header  refers to the output format. 

In  ASP . NET Core  which is corresponding to  the Output Formatters . 

 

An input format for specifying the  Header is the Content-the Type , in  the ASP . The NET Core  which is corresponding to  the Input Formatter .  

For example  POST  request  body  will need to specify the  Content-Type  for identification, the  Header  can be seen from the descriptive part of the constraint (each message must contain sufficient information to know how to process it). 

 

Guess you like

Origin www.cnblogs.com/cgzl/p/12040892.html