gpt4 book ai didi

c# - ASP.NET Core 2.0 中 RequiredAttribute 的本地化

转载 作者:太空狗 更新时间:2023-10-29 20:52:39 27 4
gpt4 key购买 nike

我在新的 .NET Core 项目中遇到本地化问题。我有 2 个项目:

  • 带有模型和 DataAnnotations 的 DataAccess 项目(例如 RequiredAttribute)
  • 具有 MVC View 等的 Web 项目。

我的愿望是将所有验证属性全局本地化到一个地方,以实现与 MVC 5 类似的行为。这可能吗?

我不想为模型/ View 等使用单独的语言文件。

对于将 SharedResources.resx 文件与本地化 DataAnnotation 消息一起使用,Microsoft 文档不是很清楚。

在 MVC 5 中我没有处理它。我只需要将语言环境设置为我的语言,一切都很好。

我尝试将 ErrorMessageResourceName 和 ErrorMessageResourceType 设置为我在 DataAccess 项目中的共享资源文件名“Strings.resx”和“Strings.de.resx”:

[Required(ErrorMessageResourceName = "RequiredAttribute_ValidationError", ErrorMessageResourceType = typeof(Strings))]

我还尝试将设置名称设置为 RequiredAttribute_ValidationError - 但它不起作用。

我已经在 Startup.cs 中添加了 .AddDataAnnotationsLocalization() - 但它似乎什么也没做。

我已经阅读了几篇文章,但找不到它不起作用的原因。

编辑:到目前为止我所拥有的:

1.) LocService类

 public class LocService
{
private readonly IStringLocalizer _localizer;

public LocService(IStringLocalizerFactory factory)
{
_localizer = factory.Create(typeof(Strings));
}

public LocalizedString GetLocalizedHtmlString(string key)
{
return _localizer[key];
}
}

2.) 使用 Strings.cs 添加文件夹“Resources”(带有虚拟构造函数的空类)

3.) 添加了带有一项“RequiredAttribute_ValidationError”的 Strings.de-DE.resx 文件

4.) 修改我的 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MessageService>();
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddSingleton<LocService>();
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
.AddDataAnnotationsLocalization(
options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(Strings));
});

services.Configure<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("de-DE"),
};

opts.DefaultRequestCulture = new RequestCulture("de-DE");
// Formatting numbers, dates, etc.
opts.SupportedCultures = supportedCultures;
// UI strings that we have localized.
opts.SupportedUICultures = supportedCultures;
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();

app.UseRequestLocalization(locOptions.Value);
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}

我已按照此处的说明进行操作,但它不起作用: https://damienbod.com/2017/11/01/shared-localization-in-asp-net-core-mvc/

请记住,我的模型保存在一个单独的项目中。

最佳答案

正如@Sven 在他对 Tseng's answer 的评论中指出的那样它仍然需要您明确指定 ErrorMessage ,这变得非常乏味。

问题出在逻辑ValidationAttributeAdapter<TAttribute>.GetErrorMessage()用于决定是否使用提供的 IStringLocalizer或不。我使用以下解决方案来解决该问题:

  1. 创建自定义 IValidationAttributeAdapterProvider使用默认 ValidationAttributeAdapterProvider 的实现像这样:

    public class LocalizedValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
    {
    private readonly ValidationAttributeAdapterProvider _originalProvider = new ValidationAttributeAdapterProvider();

    public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
    {
    attribute.ErrorMessage = attribute.GetType().Name.Replace("Attribute", string.Empty);
    if (attribute is DataTypeAttribute dataTypeAttribute)
    attribute.ErrorMessage += "_" + dataTypeAttribute.DataType;

    return _originalProvider.GetAttributeAdapter(attribute, stringLocalizer);
    }
    }
  2. Startup.ConfigureServices() 中注册适配器调用前AddMvc() :

    services.AddSingleton<Microsoft.AspNetCore.Mvc.DataAnnotations.IValidationAttributeAdapterProvider, LocalizedValidationAttributeAdapterProvider>();

我更喜欢根据实际属性使用“更严格”的资源名称,因此上面的代码将查找诸如“Required”和“DataType_Password”之类的资源名称,但这当然可以通过多种方式进行自定义。

如果您更喜欢基于属性的默认消息的资源名称,您可以这样写:

attribute.ErrorMessage = attribute.FormatErrorMessage("{0}");

关于c# - ASP.NET Core 2.0 中 RequiredAttribute 的本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48769199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com