ASP.NET核心模型绑定错误消息本地化 [英] ASP.NET Core Model Binding Error Messages Localization

查看:108
本文介绍了ASP.NET核心模型绑定错误消息本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using ASP.NET Core, and trying to localize the application. I managed to use new asp .net 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:

值'abc'对于ID无效."

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

当我在View中的ID属性中输入abc时,由于无法对字段进行模型绑定,并且在字段附近显示了验证消息,提示值'abc'对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*/
}

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

The similar issues I found on the internet were either targeted to older asp .net 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.

在这里您可以下载这篇文章中描述的完整源代码.该存储库包含 ASP.NET Core 2.0(VS 2017.3) ASP.NET Core 1.1(VS 2015)的示例:

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):

也在这里您可以看到示例,现场直播:

Also here you can see the example, live:

这些是默认错误消息,当模型绑定到属性失败时,框架会显示这些错误消息:

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.

除了上述消息外,ASP.NET Core 2.0还具有以下消息:

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.

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

要本地化ASP.NET Core模型绑定错误消息,请按照下列步骤操作:

Localize ASP.NET Core Model Binding Error Messages

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

  1. 创建资源文件-在解决方案的 Resources 文件夹下创建资源文件,并将文件命名为 ModelBindingMessages.fa.resx .名称可以是其他任何名称,但我们将使用它来创建本地化器.在此示例中,我使用的是 fa (波斯语)文化.

  1. 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:

我使用的键类似于原始消息,除了ValueMustNotBeNull的键与ValueIsInvalid相同,因此我使用了 Null值无效..

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.

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

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;
    });
}

还要在Configure方法的开头添加以下代码:

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
});

ASP.NET Core 2.0重要说明

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

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.

例如,设置 ValueIsInvalidAccessor,您应该使用SetValueIsInvalidAccessor() 这样的方法:

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核心模型绑定错误消息本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆