-
Notifications
You must be signed in to change notification settings - Fork 5
Managing Media Types
A MIME-Type is a standardized way to describe the type of a document. In the API context, it allow the client and the server to know what type of data is passed. See MIME Types.
Each MIME-type define at least the format of the object (e.g. application/json
, application/xml
) but can go deeper and define also the object itself (e.g. with vendor content type : vnd.user+json
, vnd.businesserror+xml
).
When we call a webservice (and if the api supports it), we can ask for a specific Media-Type response. The desired response body is defined with the Accept
Http-Header.
For example, if an API is able to respond either with the xml format or the json format, you can select the json from the request with the header Accept : application/json
.
If the requested Media-Type is not supported by the API, you'll get a 406 Not Acceptable
status code.
In the startup.cs
file of your dotnet core api, search for the public void ConfigureServices(IServiceCollection services)
method and customize the MVC service config like following :
services.AddMvc(setupAction => setupAction.ReturnHttpNotAcceptable = true; );
This line will automatically return the 406
in case of unsupported requested type.
(See this change in the API in the following code commit : 2e32477e732e1937956508cf727181f92d9d97e2 )
Now we want to add a new serialization format which is application/xml
. Microsoft already did the job for us, so we just have to install this Microsoft.AspNetCore.Mvc.Formatters.Xml NuGet package in our API project, and then add this simple line in the setupAction
we've seen above :
setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
(See this change in the API in the following code commit : 2e32477e732e1937956508cf727181f92d9d97e2 )
Now that we have multiple type support for the response we get from the api, it would be great to be able to pass other type (e.g. xml) for request body like a POST.
The request body is described by the Content-Type
http-header (e.g. Content-Type : application/json
). This header will inform the server that the passed body object is in the given format (here JSON).
As we already did the big job in the previous section, now we only have to add a InputFormatter like :
setupAction.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());
(See this change in the API in the following code commit : b24ae8a770addd7efbf94b062af8684fc4fea85f