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

.NET 6 MVC无法识别浏览器zh-TW文化请求问题求助

问题描述
  • 浏览器语言设置为zh-TW时,ASP.NET Core 6 MVC应用渲染简体中文内容,CurrentCulture.Name显示为zh
  • 已创建的资源文件:
    • strings.zh-CHS.resx
    • strings.zh-CHT.resx
    • Strings.zh-cn.resx
    • strings.zh-Hans.resx
    • strings.zh-Hant.resx
    • Strings.zh-TW.resx
    • strings.zh.resx
  • 配置代码中通过CultureInfo.GetCultures筛选支持的文化,调试时supportedCultures包含:zh、zh-Hans、zh-Hant、zh-Hant-TW
  • 尝试过对supportedCultures执行Reverse(),但问题未解决
解决方法
  1. 明确添加zh-TW到支持的文化列表
    自动筛选的supportedCultures里只有zh-Hant-TW,但浏览器发送的请求头是zh-TW,需要手动将zh-TW对应的CultureInfo加入列表:
// 在筛选完supportedCultures后添加
supportedCultures.Add(CultureInfo.GetCultureInfo("zh-TW"));

或者直接手动定义支持的文化,避免自动筛选的不确定性:

var supportedCultures = new List<CultureInfo>
{
    new CultureInfo("en-US"),
    new CultureInfo("zh-CN"),
    new CultureInfo("zh-TW"),
    new CultureInfo("zh-Hans"),
    new CultureInfo("zh-Hant")
};
  1. 调整请求文化的匹配逻辑
    默认的AcceptLanguageHeaderRequestCultureProvider会优先匹配父文化(比如zh-TW会匹配到zh),可以修改匹配模式为精确匹配:
var options = new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("en-US"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
};

// 获取默认的AcceptLanguage头提供者并设置精确匹配
var provider = options.RequestCultureProviders.OfType<AcceptLanguageHeaderRequestCultureProvider>().First();
provider.MatchBehavior = RequestCultureMatchBehavior.ExactMatch;
  1. 统一资源文件命名规范
    确保资源文件命名和文化名称严格对应,建议统一使用小写格式,比如strings.zh-tw.resx,避免因命名大小写不一致导致无法识别。

  2. 移除supportedCultures.Reverse()操作
    反转列表无法从根本上解决匹配逻辑问题,反而可能导致其他文化的匹配异常,建议直接移除该代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:00:01