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

.NET 7本地化资源无法找到:WebAPI与类库配置问题求助

.NET 7 WebAPI 类库本地化资源未找到问题解决方案

1. 检查资源文件的命名与配置

  • 确保类库Api.Localization中Resources文件夹下的resx文件命名符合规范:默认语言用Common.resx,多语言版本用Common.zh-CN.resx这类格式,对应的Common类需与文件名完全一致,且为public访问级别,命名空间为Api.Localization.Resources。
  • 右键resx文件→属性,将生成操作设为Embedded resource,在resx编辑器的工具栏中把访问修饰符改为Public。

2. 修正WebAPI的本地化服务配置

在Api.Gateway的Program.cs中,需明确指定资源所在的类库程序集,同时配置支持的文化:

// 添加本地化服务,指定资源路径(类库内的Resources文件夹)
services.AddLocalization(options => options.ResourcesPath = "Resources");

// 配置请求本地化规则
services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[] { "en", "zh-CN" };
    options.DefaultRequestCulture = new RequestCulture("en");
    options.SupportedCultures = supportedCultures.Select(c => new CultureInfo(c)).ToList();
    options.SupportedUICultures = supportedCultures.Select(c => new CultureInfo(c)).ToList();
});

// 注册中间件,让系统处理请求中的语言头
app.UseRequestLocalization();

注意:必须添加app.UseRequestLocalization()中间件,否则请求的文化设置不会生效。

3. 控制器中正确注入与使用

确保注入的IStringLocalizer泛型参数使用完整命名空间的资源类:

private readonly IStringLocalizer<Api.Localization.Resources.Common> _stringLocalizer;

public TestController(IStringLocalizer<Api.Localization.Resources.Common> stringLocalizer)
{
    _stringLocalizer = stringLocalizer;
}

[HttpGet("test-localization")]
public IActionResult GetLocalizedString()
{
    var testContent = _stringLocalizer["Test"];
    return Ok(new { Message = testContent });
}

请求时需在请求头中携带Accept-Language指定文化,例如Accept-Language: zh-CN,否则系统会使用默认文化。

4. 排查常见问题

  • 命名空间不匹配:资源类的命名空间必须与文件夹结构对应,即Api.Localization.Resources,否则本地化系统无法定位资源。
  • 资源嵌入失败:若resx文件的生成操作未设为Embedded resource,编译后资源不会被嵌入到类库dll中,导致无法读取。
  • 资源键名错误:确认resx文件中存在Test这个键名,且大小写一致(本地化键名区分大小写)。

内容的提问来源于stack exchange,提问作者Amar Ćatović

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 21:12:27