Localization of RequiredAttribute in ASP.NET Core 2.0

前端 未结 4 633
一生所求
一生所求 2021-01-02 03:37

I\'m struggling with localization in my new .NET Core project. I have 2 projects:

  • DataAccess project with Models and DataAnnotations (e.g. RequiredAttribute)
4条回答
  •  星月不相逢
    2021-01-02 04:10

    As @Sven points out in his comment to Tseng's answer it still requires that you specify an explicit ErrorMessage, which gets quite tedious.

    The problem arises from the logic ValidationAttributeAdapter.GetErrorMessage() uses to decide whether to use the provided IStringLocalizer or not. I use the following solution to get around that issue:

    1. Create a custom IValidationAttributeAdapterProvider implementation that uses the default ValidationAttributeAdapterProvider like this:

      public class LocalizedValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
      {
          private readonly ValidationAttributeAdapterProvider _originalProvider = new ValidationAttributeAdapterProvider();
      
          public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
          {
              attribute.ErrorMessage = attribute.GetType().Name.Replace("Attribute", string.Empty);
              if (attribute is DataTypeAttribute dataTypeAttribute)
                  attribute.ErrorMessage += "_" + dataTypeAttribute.DataType;
      
              return _originalProvider.GetAttributeAdapter(attribute, stringLocalizer);
          }
      }
      
    2. Register the adapter in Startup.ConfigureServices() Before calling AddMvc():

      services.AddSingleton();
      

    I prefer to use "stricter" resource names based on the actual attributes, so the code above will look for resource names like "Required" and "DataType_Password", but this can of course be customized in many ways.

    If you prefer resources names based on the default messages of the Attributes you could instead write something like:

    attribute.ErrorMessage = attribute.FormatErrorMessage("{0}");
    

提交回复
热议问题