.NET SDK 6(C#):独立项目中字符串资源无法正常工作
排查步骤与解决方案
1. 修正空类的命名空间与类名
- 空类必须位于SharedResources类库项目的默认命名空间下(比如
SharedResources,而非GestionTasas.Web),且类名要与resx文件的前缀完全一致。示例代码:namespace SharedResources; public class SharedResources { } - 确保resx文件命名与空类匹配:比如空类叫
SharedResources,则resx文件应为SharedResources.resx、SharedResources.es.resx等格式。
2. 检查Resx文件属性配置
选中所有resx文件,在属性面板中设置:
- 自定义工具:
PublicResXFileCodeGenerator - 访问修饰符:
Public(可在resx编辑器的「工具」菜单中设置) - 生成操作:
嵌入的资源
3. 调整本地化服务配置
在Web项目的Program.cs中,确保本地化服务正确指向类库中的资源类:
builder.Services.AddLocalization(options => options.ResourcesPath = ""); builder.Services.AddControllersWithViews() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResources.SharedResources)); });
4. 视图中正确注入与使用本地化器
- 在视图(或
_ViewImports.cshtml全局配置)中引用类库命名空间:@using SharedResources @inject IStringLocalizer<SharedResources> Localizer - 使用时调用正确的资源键:
@Localizer["YourResourceKey"]
5. 验证类库引用与依赖
- 确认Web项目已正确添加SharedResources类库的项目引用,且类库已成功编译。
- 清理解决方案并重新生成,避免旧资源缓存干扰。
内容的提问来源于stack exchange,提问作者Diego Perez
相关产品推荐
相关产品推荐

