.Net Core RequestHttpMessage AddCookies to Header in .Net Core Web Api
.Net Core RequestHttpMessage AddCookies to Header in .Net Core Web Api
我需要在我的控制器方法之一中 return HttpResponseMessage
并在少数情况下向其添加 cookie。
我参考了几篇文章,但无法解决。例如:
我使用了类似于以下内容的 .NET Framework 代码,但我在 .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,
}
});
}
到目前为止,我已尝试使用以下代码 returning 状态代码和消息。
protected IActionResult CreateInternalServerResponse<T>(T data) =>
StatusCode((int)HttpStatusCode.InternalServerError, data);
var responseMessage =
CreateInternalServerResponse(
"Call to Api failed. Response received: "
+ (jsonResp["message"]));
但我不确定如何添加 cookie。
试试下面的代码:
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;
}
我需要在我的控制器方法之一中 return HttpResponseMessage
并在少数情况下向其添加 cookie。
我参考了几篇文章,但无法解决。例如:
我使用了类似于以下内容的 .NET Framework 代码,但我在 .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,
}
});
}
到目前为止,我已尝试使用以下代码 returning 状态代码和消息。
protected IActionResult CreateInternalServerResponse<T>(T data) =>
StatusCode((int)HttpStatusCode.InternalServerError, data);
var responseMessage =
CreateInternalServerResponse(
"Call to Api failed. Response received: "
+ (jsonResp["message"]));
但我不确定如何添加 cookie。
试试下面的代码:
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;
}