using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Microsoft.Extensions.Localization; using System.ComponentModel.DataAnnotations; using System.Reflection; namespace Infrastructure.Web { public class LocalizedValidationMetadataProvider : IValidationMetadataProvider { private IStringLocalizer _localizer; public LocalizedValidationMetadataProvider(IStringLocalizerFactory factory) { this._localizer = factory.Create("Resources.Resource", Assembly.GetEntryAssembly().GetName().Name); } public void CreateValidationMetadata(ValidationMetadataProviderContext context) { var assembly = Assembly.GetExecutingAssembly(); var resources = assembly.GetManifestResourceNames(); foreach (var res in resources) { System.Diagnostics.Debug.WriteLine($"resource:{res} "); } foreach (var attribute in context.ValidationMetadata.ValidatorMetadata) { var validationAttribute = attribute as ValidationAttribute; if (validationAttribute != null && validationAttribute.ErrorMessage == null && validationAttribute.ErrorMessageResourceName == null) { var name = validationAttribute.GetType().Name; validationAttribute.ErrorMessage = _localizer.GetString(name); } } } } }