You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 6.0中如何强制[Required]验证消息为法语

ASP.NET DataAnnotations 法语验证消息全局配置解答

问题1:“The {0} field is required.” 消息来源

这条默认验证消息来自.NET框架内置的System.ComponentModel.DataAnnotations资源文件(对应DataAnnotationsResources.resx),其中的RequiredAttribute_ValidationError键值对就是该默认文本。当你未在[Required]属性中指定自定义错误消息时,框架会自动调用这个内置资源的内容。

问题2:全局修改验证消息语言(无需逐个属性配置)

有两种常用方式可以实现全局法语验证消息配置:

方式一:使用框架自带的法语本地化资源

.NET框架本身提供了多语言的DataAnnotations资源包,只需配置应用的区域性为法语即可自动加载对应语言的验证消息:

  • ASP.NET MVC(传统):在Global.asax.cs中添加区域性设置:
    protected void Application_BeginRequest()
    {
        var frenchCulture = new System.Globalization.CultureInfo("fr-FR");
        System.Threading.Thread.CurrentThread.CurrentCulture = frenchCulture;
        System.Threading.Thread.CurrentThread.CurrentUICulture = frenchCulture;
    }
    
  • ASP.NET Core:在Program.cs中配置本地化中间件:
    builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
    
    var supportedCultures = new[] { new System.Globalization.CultureInfo("fr-FR") };
    app.UseRequestLocalization(new RequestLocalizationOptions
    {
        DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("fr-FR"),
        SupportedCultures = supportedCultures,
        SupportedUICultures = supportedCultures
    });
    
    配置完成后,[Required]的默认验证消息会自动变为法语的“Le champ {0} est obligatoire.”

方式二:自定义全局资源文件覆盖默认消息

如果框架自带的法语消息不符合需求,可以创建自定义资源文件全局替换:

  1. 创建法语资源文件(如ValidationMessages.fr.resx),添加键RequiredAttribute_ValidationError,设置值为你需要的法语文本(比如“Le champ {0} est requis.”)
  2. 配置DataAnnotations使用该资源:
    • ASP.NET MVC(传统):在Global.asax.cs中设置全局资源类:
      protected void Application_Start()
      {
          DefaultModelBinder.ResourceClassKey = "ValidationMessages";
      }
      
    • ASP.NET Core:在Program.cs中配置本地化提供器:
      builder.Services.AddControllersWithViews()
          .AddDataAnnotationsLocalization(options =>
          {
              options.DataAnnotationLocalizerProvider = (type, factory) =>
                  factory.Create(typeof(ValidationMessages));
          });
      

这样所有DataAnnotations的验证消息都会从你自定义的法语资源文件中读取,无需在每个属性上单独设置ErrorMessageResourceName和ErrorMessageResourceType。


内容的提问来源于stack exchange,提问作者El MoZo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:41:58