You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 8.0 Blazor Server应用中如何获取语言Cookie?

问题分析与解决方案

针对Blazor Server应用中API端点无法获取语言Cookie的问题(Swagger请求正常,客户端请求异常),可按以下步骤排查修复:

1. 修正Cookie的SameSite与Secure配置

当Cookie的SameSite设为None时,现代浏览器要求必须同时开启Secure属性(仅通过HTTPS传输),否则会拒绝发送该Cookie。你的代码中Secure = false不符合HTTPS环境要求,需调整:

修改CultureController的Set方法中Cookie配置:

new CookieOptions
{
    Path = "/",
    SameSite = SameSiteMode.Lax, // 同站点请求优先用Lax,None需配合Secure=true
    Secure = true, // HTTPS环境下强制开启,SameSite=None时必须设置
    HttpOnly = false
}

若必须使用SameSiteMode.None(比如跨场景需求),务必保证Secure = true,否则浏览器会拦截Cookie发送。

2. 确保Blazor客户端请求携带凭证

Blazor Server中通过HttpClient发起API请求时,需显式指定包含Cookie凭证:

方式一:全局配置HttpClient

在Program.cs中添加:

builder.Services.AddHttpClient("ApiClient", client =>
{
    client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
})
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

// 注入时使用命名客户端
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("ApiClient"));

方式二:单个请求指定凭证

发送请求时添加HttpRequestMessageOptions:

var response = await httpClient.GetAsync("destinations/getPaginated/1/1/10", new HttpRequestMessageOptions
{
    Credentials = HttpCredentialsOption.Include
});

3. 验证中间件顺序(当前配置已正确,可确认)

确保请求本地化中间件UseRequestLocalization在路由和控制器映射之间,你的Program.cs顺序正确:

app.UseRouting();
app.UseRequestLocalization(localizationOptions); // 正确位置
app.MapControllers();

4. 确认Cookie作用域

已设置Path = "/",确保Cookie在整个站点范围内有效,无需调整。


内容的提问来源于stack exchange,提问作者SilverMoon17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 21:46:03