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

时间:2014-05-01 01:46:56

标签: asp.net .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>
    }        

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

1 个答案:

答案 0 :(得分:5)

它位于内容标题中:

public string GetContentType(HttpRequestMessage request) {
    return request.Content.Headers.ContentType;
}