Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add header in IHttpActionResult in Web API 2?

Hi i am developing API's using Web API 2. I know how to add header when using HttpResponseMessage. Now I am using IHttpActionResult.

Below is my sample current code.

return Content(HttpStatusCode.OK, LoginResponse);

How can I add a header when I am returning content?

Whenever I use HttpResponseMessage I will be having request object and I can add header.

Below code I tried in HttpResponseMessage.

response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Headers.AddCookies(new[] { cookie });
return response;

In this case where can I add header values?

like image 382
Niranjan Godbole Avatar asked Jul 25 '17 06:07

Niranjan Godbole


3 Answers

You can continue to use the HttpResponseMessage as you are accustom to and update the header. After which you can use the IHttpActionResult ResponseMessage(HttpResponseMessage) method to convert to IHttpActionResult

Simple example

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);
    }
}
like image 105
Nkosi Avatar answered Nov 13 '22 21:11

Nkosi


You can create a custom IHttpActionResult which decorates a real one but exposes a way to manipulate the response:

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;
    }
}

Then use this in your action:

return new CustomResult(Content(HttpStatusCode.OK, loginResponse), res => res.Headers.AddCookies(new []{ cookie}));
like image 26
peco Avatar answered Nov 13 '22 21:11

peco


You can add header by using this code:

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

or this

response.Headers.Add("Some-Header", value);
like image 25
Rostech Avatar answered Nov 13 '22 22:11

Rostech