I have trouble finding the way to check request content type in ASP.NET Web Api. Is there a way I can check request content type whether it is application/xml or application/json at controller level?
any help would be appreciated.
Content-type: which requests to API to represent data in this type. Accept: The acceptable media types for the response, such as “application/json,” “application/xml,” or a custom media type such as "application/vnd. example+xml". Accept-Charset: The acceptable character sets, such as UTF-8 or ISO 8859-1.
The Content-Type field in the HTTP headers indicates in which format the data is sent to, or returned by, the HTTP methods of the Rule Execution Server REST API.
The media type determines how Web API serializes and deserializes the HTTP message body. Web API has built-in support for XML, JSON, BSON, and form-urlencoded data, and you can support additional media types by writing a media formatter. To create a media formatter, derive from one of these classes: MediaTypeFormatter.
The accepted answer is misleading because its answers the question for the MVC paradigm rather than Web API, also pointed out by @ataravati. The following is an example of how to access the ContentType inside of a Web API controller action.
[HttpPost]
[Route("api/post")]
public void Post()
{
var contentType = this.Request.Content.Headers.ContentType;
//other stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With