DataType 和 Range 数据注释不会本地化错误消息

问题描述 投票:0回答:1

我不明白为什么在 asp.net 7.0 razor 页面应用程序中,数据注释错误消息的本地化适用于除“DataType”属性之外的所有属性,其中显示的错误消息始终为英文。

“Range”属性存在同样的问题,当字段为空时,您会收到相同的“DataType”错误消息。

此外,使用 ErrorMessageResourceName 和 ErrorMessageResourceType 属性也无法进行本地化。

有两个资源文件 ValidationMessages.resx 和 ValidationMessages.it.resx,都包含所有错误消息。

数据模型的一部分:

    [Display(Name = "Year go")]
    [Required(ErrorMessage = "Required")]
    [Range(2000, 2100, ErrorMessage = "Range")]
    //[Range(2000, 2100, ErrorMessageResourceName = nameof(ValidationMessages.Range), ErrorMessageResourceType = typeof(ValidationMessages))]
    public int YearGo { get; set; }

    //[DataType(DataType.Date, ErrorMessage = "DataType")]
    [DataType(DataType.Date, ErrorMessageResourceName = nameof(ValidationMessages.DataType), ErrorMessageResourceType = typeof(ValidationMessages))]
    public DateTime ReleaseDate { get; set; }

    [Range(1, 10, ErrorMessage = "Range")]
    //[DataType(DataType.Currency, ErrorMessage = "DataType")]
    [DataType(DataType.Currency, ErrorMessageResourceName = nameof(ValidationMessages.DataType), ErrorMessageResourceType = typeof(ValidationMessages))]
    [Column(TypeName = "decimal(18, 2)")]
    public decimal? Price { get; set; } 

节目:

public static void Main(string[] args)
{
    string culture = "it";
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);

    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.
    builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

    var supportedCultures = new[] { new CultureInfo("it"), new CultureInfo("en-US") };
    builder.Services.Configure<RequestLocalizationOptions>(options =>
    {
        options.DefaultRequestCulture = new RequestCulture(culture);
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
    });

    builder.Services.AddDbContext<OWsefaWebContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("OWsefaWebContext") ?? throw new InvalidOperationException("Connection string 'OWsefaWebContext' not found.")));

    // Add services to the container.
    builder.Services.AddRazorPages()
        .AddDataAnnotationsLocalization(opts =>
        {
            opts.DataAnnotationLocalizerProvider = (type, factory) =>
            {
                var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName!);
                return factory.Create(nameof(SharedResource), assemblyName.Name!);
            };
        })
        .AddViewLocalization();


    var app = builder.Build();

    using (var scope = app.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        DataInitializer.Initialize(services);
    }

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();
    app.MapRazorPages();

    app.UseRequestLocalization();

    app.Run();
}

屏幕截图:

asp.net-core razor-pages data-annotations
1个回答
0
投票

我检查了你的代码,发现问题是系统返回的错误信息不是来自

DataTypeAttribute
,而是来自.NET的绑定系统。

绑定系统的消息源自

DefaultModelBindingMessageProvider 
,您可以设置各种方法来提供自定义错误消息。

您可以在

AddMvcOptions
方法中设置消息,这是我在代码中所做的更改,以使其与提供的资源一起使用。

builder.Services.AddRazorPages()
    .AddDataAnnotationsLocalization(opts =>
    {
        opts.DataAnnotationLocalizerProvider = (type, factory) =>
        {
            var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName!);
            return factory.Create(nameof(SharedResource), assemblyName.Name!);
        };
        
    })
    .AddViewLocalization()
    .AddMvcOptions(options => {
        options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor(
            (arg) => {
                return string.Format(CultureInfo.CurrentCulture, Resources.SharedResource.Message_DataType, arg);
        });
    });

由于某些原因,您需要将当前文化指定为

string.Format
才能使用意大利语资源。

© www.soinside.com 2019 - 2024. All rights reserved.