ASP.NET Core 模型绑定错误消息本地化

编程入门 行业动态 更新时间:2024-10-24 16:23:42
本文介绍了ASP.NET Core 模型绑定错误消息本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 ASP.NET Core,并尝试本地化应用程序.我设法使用新 asp 核心资源来本地化控制器和视图,并使用旧 资源来本地化模型验证的错误消息.但是,当错误消息未链接到模型字段注释(如必需")并且模型绑定的数据不正确(如需要数字的文本)时,我收到如下错误,我是无法本地化:

值 'abc' 对 ID 无效."

当我在 View 中为 ID 属性输入 abc 时,由于无法对字段进行模型绑定并显示验证字段附近的消息,说值 'abc' 对 ID 无效.".这是我正在使用的课程:

公共类国家:IHasID{公共 int ID { 获取;放;}[必需(ErrorMessageResourceType = typeof(L.Val),ErrorMessageResourceName = "NameR")][MaxLength(100, ErrorMessageResourceType = typeof(L.Val),ErrorMessageResourceName = "Max")]公共字符串名称 { 获取;放;}/*其他一些属性*/}

我在互联网上发现的类似问题要么针对较旧的asp 版本,要么没有帮助我解决问题.

解决方案

要自定义框架模型绑定错误消息,您需要为

我使用的键就像原始消息,除了 ValueMustNotBeNull 的键与 ValueIsInvalid 相同,所以我使用了 Null 值无效. 为它.

  • 配置选项 - 在 ConfigureServices 方法中,添加 Mvc 时,配置其选项以设置 ModelBindingMessageProvider 的消息访问器:

    public void ConfigureServices(IServiceCollection services){services.AddLocalization(options => { options.ResourcesPath = "Resources"; });services.AddMvc(options =>{var F = services.BuildServiceProvider().GetService();var L = F.Create("ModelBindingMessages", "AspNetCoreLocalizationSample");options.ModelBindingMessageProvider.ValueIsInvalidAccessor =(x) =>L["值 '{0}' 无效.", x];options.ModelBindingMessageProvider.ValueMustBeANumberAccessor =(x) =>L["字段 {0} 必须是数字.", x];options.ModelBindingMessageProvider.MissingBindRequiredValueAccessor =(x) =>L["未提供 '{0}' 属性的值.", x];options.ModelBindingMessageProvider.AttemptedValueIsInvalidAccessor =(x, y) =>L["值 '{0}' 对 {1} 无效.", x, y];options.ModelBindingMessageProvider.MissingKeyOrValueAccessor =() =>L["需要一个值."];options.ModelBindingMessageProvider.UnknownValueIsInvalidAccessor =(x) =>L["提供的值对于 {0} 无效.", x];options.ModelBindingMessageProvider.ValueMustNotBeNullAccessor =(x) =>L["空值无效.", x];}).AddDataAnnotationsLocalization().AddViewLocalization();services.Configure(options =>{var supportedCultures = new[]{new CultureInfo("en"), new CultureInfo("fa")};options.DefaultRequestCulture = new RequestCulture("en", "en");options.SupportedCultures = supportedCultures;options.SupportedUICultures = supportedCultures;});}

    还要在Configure方法的开头添加这段代码:

    var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("fa") };app.UseRequestLocalization(new RequestLocalizationOptions(){DefaultRequestCulture = new RequestCulture(new CultureInfo("en")),支持的文化 = 支持的文化,支持的UICultures = 支持的文化});

  • ASP.NET Core 2.0 的重要说明

    在 ASP.NET Core 2.0 中,模型绑定消息提供程序属性已经获得只读,但已为每个属性添加了一个 setter 方法.

    例如设置ValueIsInvalidAccessor,你应该使用 SetValueIsInvalidAccessor()这种方法:

    options.ModelBindingMessageProvider.SetValueIsInvalidAccessor ((x) =>L["值 '{0}' 无效.", x]);

    I'm using ASP.NET Core, and trying to localize the application. I managed to use new asp core resources to localize controllers and views, and old resources to localize error messages for model validation. However, when the error message is not linked to a model field annotation (like "Required") and the data for model binding is incorrect (like a text where a number is expected), I receive the error like below, which I'm unable to localize:

    "The value 'abc' is not valid for ID."

    When I enter abc for ID property in View, since the model binding can not be done to the field and it shows a validation message near the field, saying "The value 'abc' is not valid for ID.". Here is the class I'm using:

    public class Country : IHasID { public int ID { get; set; } [Required(ErrorMessageResourceType = typeof(L.Val), ErrorMessageResourceName = "NameR")] [MaxLength(100, ErrorMessageResourceType = typeof(L.Val), ErrorMessageResourceName = "Max")] public string Name { get; set; } /*Some other properties*/ }

    The similar issues I found on the internet were either targeted to older asp version, or else didn't help me solve the problem.

    解决方案

    To customize framework model binding error messages, you need to set custom accessors for different error message accessors of ModelBindingMessageProvider.

    Example

    Here you can download a full source code of what is described in this post. The repository contains example for ASP.NET Core 2.0 (VS 2017.3) and ASP.NET Core 1.1 (VS 2015):

    • r-aghaei/AspNetCoreLocalizationSample

    Also here you can see the example, live:

    • aspnetcorelocalizationsample.azurewebsites
    Default Error Messages

    These are default error messages which the framework shows when model binding to a property fails:

    MissingBindRequiredValueAccessor A value for the '{0}' property was not provided. MissingKeyOrValueAccessor A value is required. ValueMustNotBeNullAccessor The value '{0}' is invalid. AttemptedValueIsInvalidAccessor The value '{0}' is not valid for {1}. UnknownValueIsInvalidAccessor The supplied value is invalid for {0}. ValueIsInvalidAccessor The value '{0}' is invalid. ValueMustBeANumberAccessor The field {0} must be a number.

    In addition to above messages, ASP.NET Core 2.0 have these messages as well:

    MissingRequestBodyRequiredValueAccessor A non-empty request body is required. NonPropertyAttemptedValueIsInvalidAccessor The value '{0}' is not valid. NonPropertyUnknownValueIsInvalidAccessor The supplied value is invalid. NonPropertyValueMustBeANumberAccessor The field must be a number.

    Localize ASP.NET Core Model Binding Error Messages

    To localize ASP.NET Core model binding error messages, follow these steps:

  • Create Resource File - Create a resource file under Resources folder in your solution and name the file ModelBindingMessages.fa.resx. The name can be anything else but we will use it to create a localizer. In the example, I used fa (Persian) culture.

  • Add Resource Keys - Open the resource file and add keys and values which you want to use for localizing error messages. I used keys and values like below image:

    Keys which I used are like original messages, except the key for ValueMustNotBeNull which was the same as ValueIsInvalid, so I used Null value is invalid. for it.

  • Configure Options - In ConfigureServices method, when adding Mvc, configure its options to set message accessors for ModelBindingMessageProvider:

    public void ConfigureServices(IServiceCollection services) { services.AddLocalization(options => { options.ResourcesPath = "Resources"; }); services.AddMvc(options => { var F = services.BuildServiceProvider().GetService<IStringLocalizerFactory>(); var L = F.Create("ModelBindingMessages", "AspNetCoreLocalizationSample"); options.ModelBindingMessageProvider.ValueIsInvalidAccessor = (x) => L["The value '{0}' is invalid.", x]; options.ModelBindingMessageProvider.ValueMustBeANumberAccessor = (x) => L["The field {0} must be a number.", x]; options.ModelBindingMessageProvider.MissingBindRequiredValueAccessor = (x) => L["A value for the '{0}' property was not provided.", x]; options.ModelBindingMessageProvider.AttemptedValueIsInvalidAccessor = (x, y) => L["The value '{0}' is not valid for {1}.", x, y]; options.ModelBindingMessageProvider.MissingKeyOrValueAccessor = () => L["A value is required."]; options.ModelBindingMessageProvider.UnknownValueIsInvalidAccessor = (x) => L["The supplied value is invalid for {0}.", x]; options.ModelBindingMessageProvider.ValueMustNotBeNullAccessor = (x) => L["Null value is invalid.", x]; }) .AddDataAnnotationsLocalization() .AddViewLocalization(); services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new[]{new CultureInfo("en"), new CultureInfo("fa")}; options.DefaultRequestCulture = new RequestCulture("en", "en"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); }

    Also add this code at beginning of Configure method:

    var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("fa") }; app.UseRequestLocalization(new RequestLocalizationOptions() { DefaultRequestCulture = new RequestCulture(new CultureInfo("en")), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures });

  • Important Note for ASP.NET Core 2.0

    In ASP.NET Core 2.0, model binding message provider properties has got read only, but a setter method for each property has been added.

    For example, to set ValueIsInvalidAccessor, you should use SetValueIsInvalidAccessor() method this way:

    options.ModelBindingMessageProvider.SetValueIsInvalidAccessor ( (x) => L["The value '{0}' is invalid.", x]);

    更多推荐

    ASP.NET Core 模型绑定错误消息本地化

    本文发布于:2023-11-15 06:33:31,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1591997.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:绑定   模型   错误   消息   ASP

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!