2

I need to return HttpResponseMessage in one of my controller methods and add a cookie to it in a few cases.

I've referred through few articles but couldn't get it resolved. For instance:

I've used .NET Framework code similar to what's below, but I need it in .NET Core:

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, content);

if (!string.IsNullOrEmpty(cookieToken))
{
    response.Headers.AddCookies(new[]
    {
        new CookieHeaderValue("MyCookie", cookieToken)
        {
            Expires = DateTimeOffset.Now.AddHours(4),
            Path = "/",
            HttpOnly = true,
            Secure = true,
        }
    });
}

So far, I've tried the below code for returning status codes and messages.

protected IActionResult CreateInternalServerResponse<T>(T data) =>
    StatusCode((int)HttpStatusCode.InternalServerError, data);

     
var responseMessage = 
    CreateInternalServerResponse(
        "Call to  Api failed. Response received: " 
        + (jsonResp["message"]));

But I'm not sure how I can add a cookie.

ruffin
  • 16,507
  • 9
  • 88
  • 138
  • 1
    What's the issue you are facing? – Chetan Jan 13 '21 at 23:57
  • I dont have HttpResponseMessage, Even if I use Response.Headers , it doesnt have addcookie. Other problem is CookieHeaderValue accepts Dictionary. – user6095576 Jan 14 '21 at 04:07
  • Can you share little bit more context? this is code is part of the an API Controller? If I understand it correctly you want to add some cookies to the response returned from your API, is that right? Can your share the code which returns a response without cookie? – Chetan Jan 14 '21 at 04:20
  • Yes. I've added IActionResult for without cookie response. But I dont know how to proceed for cookies case. I've edited the original post – user6095576 Jan 14 '21 at 05:54
  • https://stackoverflow.com/questions/52191376/using-cookies-in-asp-net-core-2-1 – Chetan Jan 14 '21 at 08:31
  • https://asp.mvc-tutorial.com/httpcontext/cookies/ – Chetan Jan 14 '21 at 08:32
  • Thanks Chetan, stackoverflow response helped too. – user6095576 Jan 14 '21 at 08:39

1 Answers1

3

Try the below codes:

public IActionResult Get()
{
    //...

    var responseMessage = CreateInternalServerResponse("Call to  Api failed. Response received: " + (jsonResp["message"]));
    
    Response.Cookies.Append("MyCookie", "cookieToken", new CookieOptions()
    {
        Expires = DateTimeOffset.Now.AddHours(4),
        Path = "/",
        HttpOnly = true,
        Secure = true,
    });

    return responseMessage;
}
mj1313
  • 7,930
  • 2
  • 12
  • 32