在我的应用程序中,我有 2 个项目,MyApp.Web 和 MyApp.ClassLibrary 项目。在
ClassLibrary
项目中,我有 AccountType
枚举,我正在尝试本地化。我可以使用标准 SharedResources
设置来实现它,但我想为 ClassLibrary
使用单独的资源文件
我得到的错误是:
InvalidOperationException:无法检索属性“名称”,因为本地化失败。类型“MyApp.ClassLibrary.AccountResources”不是公共的或不包含名称为“Active”的公共静态字符串属性。
AccountType
枚举:
namespace MyApp.ClassLibrary.Accounts;
public enum AccountType
{
[Display(Name = "Active", ResourceType = typeof(AccountResources))]
Active,
[Display(Name = "Disabled", ResourceType = typeof(AccountResources))]
Disabled,
[Display(Name = "Demo", ResourceType = typeof(AccountResources))]
Demo
}
我在 ClassLibrary 项目的根目录下创建了一个虚拟类:
namespace MyApp.ClassLibrary;
public class AccountResources
{
}
我在 Web 项目中创建了 Resources 文件夹,并将
Accounts.AccountResources.uz-Latn-UZ.resx
文件放在那里。
在
Program.cs
中,我的配置如下:
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).AddDataAnnotationsLocalization(options => {
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResources));
});
注意: 你可以注意到我在这里使用
SharedResources
并且它们 do work 用于 ClassLibrary
中的枚举。但我更愿意为 ClassLibrary 项目提供单独的资源文件,包括枚举的本地化。
Accounts.AccountResources.uz-Latn-UZ.resx
文件的访问修饰符设置为“无代码生成”,与SharedResources.uz-Latn-UZ.resx
中的相同(有效)。
我试图移动 ClassLibrary 的 Resources 文件夹中的
Accounts.AccountResources.uz-Latn-UZ.resx
,但我得到了同样的错误。
这个配置错了吗?有没有不使用
SharedResources
的正确方法来实现所需的设置?
谢谢!
你可以试试这段代码。 在根目录下创建
AccountResources.resx
文件,无需注册服务。将访问修饰符设置为“公共”。产品.cs
public class Product
{
public AccountType AccountType1 { get; set; }
}
public enum AccountType
{
[Display(Name = "Active", ResourceType = typeof(AccountResources))]
Active,
[Display(Name = "Disabled", ResourceType = typeof(AccountResources))]
Disabled,
[Display(Name = "Demo", ResourceType = typeof(AccountResources))]
Demo
}
控制器
public IActionResult Index()
{
var result = new Product() { accountType = AccountType.Demo };
return View(result);
}
Index.cshtml
@model WebApplication9.Models.Product
@Html.DisplayTextFor(m=>m.accountType)