如何在 ASP.NET Core Web API 项目中设置 cookie
我正在尝试为Localhost的ASP.NET Core Web API项目设置一个cookie,但是Cookie仅通过响应标头发送而不设置在浏览器中。我已经尝试
withcredentials: true
在cookie中设置,但这无效。
这是控制器的代码:
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);
这是该响应的网络信息的片段:
另外,我的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();
我没有收到任何错误,cookie无法在所有浏览器中设置。我正在使用SSL的自签名证书,并且正在使用.NET Core 6.0。我通常在以前的.NET Core中从未遇到过问题,但是这个问题对我来说很奇怪。
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. I have tried setting
withcredentials: true
in the cookie, but that did not work.
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:
Also, my program.cs file looks like this:
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. I'm using a self-signed certificate for ssl and I'm using .NET Core 6.0. I usually never had issues in previous versions of .NET Core, but this issue is very odd to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您设置
httponly = true
时,cookie仅出现在请求标题中,并且客户端脚本无法访问。When you set
HttpOnly = true
, cookies only appear in the request header and cannot be accessible by the client script.