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

.NET 7下ASP.NET Core本地化完全失效,求排查方案

ASP.NET Core 7 Razor页面本地化失效问题修复

问题场景

在VS2022创建的ASP.NET Core 7 Razor Pages项目中,已配置本地化服务、资源路径及支持的文化,但页面仅显示资源键Welcome,通过URL参数?ui-culture=vi-VN切换语言无效果。

遗漏的配置项及修复方案

1. 完善RequestLocalizationOptions配置

当前代码仅设置了SupportedUICultures,缺少SupportedCultures配置,且默认请求文化需同时指定文化与UI文化。显式配置URL参数提供器可确保语言切换优先级:

builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[]
    {
        new CultureInfo("en-US"),
        new CultureInfo("vi-VN")
    };

    options.DefaultRequestCulture = new RequestCulture("en-US", "en-US");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;

    // 确保URL参数优先用于切换语言
    options.RequestCultureProviders.Insert(0, new QueryStringRequestCultureProvider());
});

2. 修正资源文件命名与访问权限

Razor Pages的资源文件需严格匹配页面路径,且访问修饰符必须为public:

  • 若Index.cshtml位于Pages文件夹下,资源文件命名应为:
    • Resources/Pages.Index.en-US.resx(英文资源)
    • Resources/Pages.Index.vi-VN.resx(越南语资源)
  • 右键资源文件 → 属性:
    • 生成操作:设为嵌入式资源
    • 自定义工具:设为ResXFileCodeGenerator
  • 打开.resx文件,右上角选择访问修饰符为public(默认internal会导致IViewLocalizer无法读取)

3. 调整中间件顺序

UseRequestLocalization必须放在UseRouting之前、UseStaticFiles之后,确保文化设置在路由解析前生效:

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();

// 本地化中间件需在路由中间件之前
app.UseRequestLocalization();

app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();

app.Run();

4. 验证资源键匹配

确认.resx文件中存在Welcome键,且对应语言的取值正确(如英文为Welcome,越南语为Chào mừng)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 18:52:48