How to return content in specified 'Accept' format from Web API aciton

I have a Web API controller action where I want to set response headers and also return the content in the requested format specified by the Accept header.

Unfortunately if I'm using a typed action or IHttpActionResult for the action's return type, I can't set the headers, but the content negotiation works.

I'd have to return HttpResponseMessage to be able to specify headers in the action, but then I need to specify the formatter for the ObjectContent . Although I'm only supporting XML or JSON types, I still don't want to burn in ugly conditionals to check what the return type should be.

Is there a way to do this nicely, without filters, attributes and custom generic return types?

public HttpResponseMessage Post([FromBody]QueryModel model)
{
    var data = _svc.Query(model);

    var resp = new HttpResponseMessage(HttpStatusCode.OK);
    // set headers
    resp.Content = new ObjectContent(typeof(ResponseModel), data, /* CAN YOU NOT GUESS */);
    return resp;
}

解决方案实际上很简单, Request对象有一个CreateResponse()方法来创建一个HttpResponseMessage

public HttpResponseMessage Post([FromBody]QueryModel model)
{
    var data = _svc.Query(model);

    var resp = Request.CreateResponse(HttpStatusCode.OK, data);
    resp.Content.Headers.Add("X-Moo", "Boo");
    return resp;
}
链接地址: http://www.djcxy.com/p/20412.html

上一篇: ASP.NET web api返回XML而不是JSON

下一篇: 如何从Web API aciton以指定的'Accept'格式返回内容