如何在Web API 2中的IHttpActionResult中添加头?

时间:2017-07-25 06:03:33

标签: c# .net asp.net-web-api asp.net-web-api2

您好我正在使用Web API 2开发API。我知道在使用IHttpActionResult时如何添加标头。现在我正在使用return Content(HttpStatusCode.OK, LoginResponse);

以下是我的当前示例代码。

HttpResponseMessage

如何在返回内容时添加标题?

每当我使用HttpResponseMessage时,我都会有请求对象,我可以添加标题。

我在response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response.Headers.AddCookies(new[] { cookie }); return response; 尝试了以下代码。

GLControl

在这种情况下,我可以在哪里添加标题值?

3 个答案:

答案 0 :(得分:3)

你可以创建一个自定义IHttpActionResult来装饰一个真实的,但是暴露了一种操纵响应的方法:

public class CustomResult : IHttpActionResult
{
    private readonly IHttpActionResult _decorated;
    private readonly Action<HttpResponseMessage> _response;

    public CustomResult(IHttpActionResult decorated, Action<HttpResponseMessage> response)
    {
        _decorated = decorated;
        _response = response;
    }

    public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = await _decorated.ExecuteAsync(cancellationToken);

        _response(response);

        return response;
    }
}

然后在你的行动中使用它:

return new CustomResult(Content(HttpStatusCode.OK, loginResponse), res => res.Headers.AddCookies(new []{ cookie}));

答案 1 :(得分:3)

您可以按照惯例继续使用HttpResponseMessage并更新标头。之后,您可以使用IHttpActionResult ResponseMessage(HttpResponseMessage)方法转换为IHttpActionResult

简单示例

public class MyApiController : ApiController {

    public IHttpActionResult MyExampleAction() {
        var LoginResponse = new object();//Replace with your model
        var cookie = new CookieHeaderValue("name", "value");//Replace with your cookie

        //Create response as usual
        var response = Request.CreateResponse(System.Net.HttpStatusCode.OK, LoginResponse);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        response.Headers.AddCookies(new[] { cookie });
        //Use ResponseMessage to convert it to IHttpActionResult
        return ResponseMessage(response);
    }
}

答案 2 :(得分:1)

您可以使用以下代码添加标题:

HttpContext.Current.Response.AppendHeader("Some-Header", value);

或者

response.Headers.Add("Some-Header", value);