Search code examples
c#asp.netasp.net-web-apiodataasp.net-web-api2

Creating cookie when using odata and web api 2


How do I set a cookie when using Web api 2 and odata. I am new to this api and traditionally I used the context.Response but it does not seem to be avaliable here.

This is a part of my controller code:

public async Task<IHttpActionResult> Post(Order Order)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    context.Orders.Add(Order);
    await context.SaveChangesAsync();

    return Created(Order);
}

Solution

  • You can write your own DelegatingHandler to add the cookie you need into the response.

    Check the part "Example: Set and Retrieve Cookies in a Message Handler":

    http://www.asp.net/web-api/overview/working-with-http/http-cookies

    For how to insert a message handler, check this:"Per-Route Message Handlers"

    http://www.asp.net/web-api/overview/working-with-http/http-message-handlers