简体   繁体   English

如何在 ASP.NET Core Web API 项目中设置 cookie

[英]How to set a cookie in a ASP.NET Core Web API project

I'm attempting to set a cookie for my ASP.NET Core Web API project in localhost, but the cookie only gets sent through the response header and not set in the browser.我试图在 localhost 中为我的 ASP.NET Core Web API 项目设置一个 cookie,但 cookie 仅通过响应标头发送,而不是在浏览器中设置。 I have tried setting我试过设置

withcredentials: true

in the cookie, but that did not work.在 cookie 中,但这不起作用。

Here is the code of the controller:这是控制器的代码:

string token = "Some string";
var cookieOptions = new CookieOptions()
    {
        IsEssential = true,
        Expires = DateTime.Now.AddMinutes(30),
        Secure = true,
        HttpOnly = true,
        SameSite = SameSiteMode.None
    };

Response.Cookies.Append("XSRF_Auth", token, cookieOptions);

Here is a snippet of the network information for that response:以下是该响应的网络信息片段:

Response Information响应信息

Also, my program.cs file looks like this:另外,我的 program.cs 文件如下所示:

var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
string[] origins = {"https://localhost:4200"};

builder.Services.AddCors();

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins(origins));

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

I'm not receiving any errors and the cookie fails to get set in all browsers.我没有收到任何错误,并且无法在所有浏览器中设置 cookie。 I'm using a self-signed certificate for ssl and I'm using .NET Core 6.0.我正在为 ssl 使用自签名证书,并且正在使用 .NET Core 6.0。 I usually never had issues in previous versions of .NET Core, but this issue is very odd to me.我通常在以前版本的 .NET Core 中从未遇到过问题,但这个问题对我来说很奇怪。

当您设置HttpOnly = true时,cookie 仅出现在请求标头中,客户端脚本无法访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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