Search code examples
asp.net-web-apiasp.net-core-localization

Asp.net core web api Localization DataAnnotation custom attribute


I'm trying to use localization with resource files, but it's not working, just for custom required attribute

public class RequiredIntAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        bool isValid = base.IsValid(value);

        if (isValid)
        {
            isValid =  int.Parse(value.ToString()) != 0;
        }

        return isValid;
    }
}

public class SalonForInsertDto
{

    public string Name { get; set; }
    public string NameEn { get; set; }

    [RequiredInt(ErrorMessage = "the userId is required")]
    public int UserId { get; set; }
}

Solution

  • In your Configure method add:

    //localization & globalization
    var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(locOptions.Value);
    

    Then in your custom validator class you add:

    var _localizationService = (IStringLocalizer<SalonForInsertDto>)validationContext.GetService(typeof(IStringLocalizer<SalonForInsertDto>));
    

    and then you are now able to get the localized string value from the resource file like:

    _localizationService["How are you?"]
    

    You can read about IStringLocalizer object and it's working in official docs.