I have gone through quite a bit of SO questions like:
Localise Display DataAnnotation without the Name Attribute in .NET Core 5 ViewModel
and examples such as these:
but I'm unable to solve the problem I have.
My DTO exists in a separate assembly, Dto.dll
. I have this DTO for user signup:
/// <summary>
/// Gets or sets the account e-mail.
/// </summary>
[Required(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = nameof(Strings.EmailValidation))]
[EmailAddress(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = nameof(Strings.EmailFormatValidation))]
[StringLength(DtoConstants.EmailMaxLength, MinimumLength = DtoConstants.EmailMinLength)]
[Display(ResourceType = typeof(Strings), Name = nameof(Strings.EmailName))]
public string Email { get; set; }
/// <summary>
/// Gets or sets the user's password.
/// </summary>
[Required(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = nameof(Strings.PasswordValidation))]
[StringLength(DtoConstants.PasswordMaxLength, ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = nameof(Strings.PasswordLengthValidation), MinimumLength = DtoConstants.PasswordMinLength)]
[DataType(DataType.Password)]
[Display(ResourceType = typeof(Strings), Name = nameof(Strings.PasswordName))]
public string Password { get; set; }
/// <summary>
/// Gets or sets the user's confirm password.
/// </summary>
[Required(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = nameof(Strings.ConfirmPasswordValidation))]
[Compare(nameof(Password), ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = nameof(Strings.PasswordsDoNotMatch))]
[DataType(DataType.Password)]
[Display(ResourceType = typeof(Strings), Name = nameof(Strings.ConfirmPasswordName))]
public string ConfirmPassword { get; set; }
All the Strings.*
resources are in a Strings.resx
file in the same assembly.
My Web API is in a different assembly, webapi.dll
, and I have this in my Program.cs
:
builder.Services.AddControllers()
.AddDataAnnotationsLocalization()
.AddViewLocalization();
And when I send in a bad request using Swagger, ModelState
validation automatically kicks in, and sends this response.
Notice that I get all the error messages correctly (the ones shown with white tick marks), as defined in the Strings.resx
(in the dto.dll
), but the "Display Name" of the property is not being returned (the one with white X marks). "ConfirmPassword" should be localized as "Confirm Password" and "Password" should be localized as "Secret" (that's what I have defined in Strings.resx
)
Does anyone know why data annotations localization is working for validation error messages, but not for display name of the properties?