ASP Web API:获取POST请求的内容类型

fer*_*olo 3 .net asp.net asp.net-mvc json web-services

我需要解析一个JSON或BSON对象.我在ApiController控制器类中的方法是这样定义的:

[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>
    }        
Run Code Online (Sandbox Code Playgroud)

问题:如何实施该GetContentType(HttpRequestMessage request)方法?

Bre*_*een 5

它位于Content标头中:

public string GetContentType(HttpRequestMessage request) {
    return request.Content.Headers.ContentType;
}
Run Code Online (Sandbox Code Playgroud)