【问题标题】:Data annotation localization with ASP.Net Core使用 ASP.Net Core 进行数据注释本地化
【发布时间】:2020-03-15 20:46:28
【问题描述】:

在“经典”ASP.Net MVC 中,我们可以使用数据注释属性 ErrorMessageResourceName 和 ErrorMessageResourceType 来指定应该使用哪个资源文件来本地化注释消息.我已经看到很多帖子和文章展示了如何在 ASP.Net Core 中使用共享资源文件,但是如果我有多个共享资源(例如,UserMessages.resx 用于我的用户视图模型和 ProductMessages. resx 用于我的产品视图模型)。有没有办法使用 IStringLocalizerFactory 以便可以使用多个资源文件(以及如何指定在密钥重复的情况下使用哪一个)?

谢谢

【问题讨论】:

  • 参考这个docs,并将services.AddMvc().AddDataAnnotationsLocalization()添加到你的startup.cs,
  • 已经看过了,但我想使用多个共享资源(请参阅下面的评论)

标签: c# asp.net-core localization data-annotations


【解决方案1】:

这是一个如下所示的工作演示:

1.型号:

public class UserModel
{
    [Required(ErrorMessage = "The Name field is required.")]
    [Display(Name = "Name")]

    public string Name { get; set; }
}
public class ProductModel
{
    [Required(ErrorMessage = "The Name field is required.")]
    [Display(Name = "Name")]

    public string Name { get; set; }
}

2.查看:

@model UserModel   
@*for ProductModel's view,just change the @mdoel*@
@*@model ProductModel*@

<form asp-action="TestUser">
    <div>
        <div class="form-group">
            <label asp-for="Name" class="control-label"></label>
            <input asp-for="Name" class="form-control" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        <div class="form-group">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </div>
</form>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

3.Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
            opts => { opts.ResourcesPath = "Resources"; })
            .AddDataAnnotationsLocalization();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/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();
        }
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("fr"),
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

4.资源文件:

位置

UserModel 资源文件内容:

ProductModel 资源文件内容:

5.结果:

【讨论】:

  • 感谢您的回答,但我的问题是:如何为多个视图模型使用相同的资源文件(例如:CreateUserViewModel、EditUserViewModel)。基于同一实体的视图模型共享许多验证,因此我想重用我的消息。这就是我想要完成的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2022-06-11
相关资源
最近更新 更多