Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check request content type in ASP.Net Web API?

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.

like image 894
user1186065 Avatar asked Jul 10 '12 15:07

user1186065


People also ask

What is Content-Type in Web API?

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.

What is Content-Type in REST API?

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.

What is MediaTypeFormatter in Web 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.


1 Answers

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
}
like image 176
Morgan Kenyon Avatar answered Oct 04 '22 20:10

Morgan Kenyon