简体   繁体   中英

.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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM