Search code examples
c#asp.net-coreasp.net-apicontroller

.Net Core RequestHttpMessage AddCookies to Header in .Net Core Web Api


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.


Solution

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