Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP Web APIs: Get content type of POST request

I need to parse a JSON or BSON object. My method at ApiController controller class is defined this way:

[HttpPost]
public object ReceiveObjectAction()
{
    JObject body;
    var contentType = GetContentType(Request);
    if (contentType == "application/json") {
        body = JObject.Parse(Request.Content.ReadAsStringAsync().Result);
    } else if (contentType == "application/bson") {
        using (var reader = new BsonReader(Request.Content.ReadAsStreamAsync().Result))
        {
            body = (JObject)JToken.ReadFrom(reader);
        }
    } else {
        // throw bad request.
    }

    // process body, etc.
}

    public string GetContentType(HttpRequestMessage request) {
        <your answer here>
    }        

Question: How can I implement the GetContentType(HttpRequestMessage request) method?

like image 587
fernacolo Avatar asked Dec 09 '25 03:12

fernacolo


1 Answers

It's in the Content header:

public string GetContentType(HttpRequestMessage request) {
    return request.Content.Headers.ContentType;
}
like image 86
Brendan Green Avatar answered Dec 10 '25 16:12

Brendan Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!