Culture in web API not used by FluentValidation
I have a web API and in global.asax I set the culture like this:
protected void Application_PostAuthenticateRequest()
{
var culture = CultureInfo.CreateSpecificCulture("nl-BE");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
I added Fluent Validation for .NET nuget and so in bin folder I have /nl/FluentValidation.resources.dll.
Next, I have a validator like:
public class AddWeightCommandValidator : AbstractValidator<AddWeightCommand>
{
public AddWeightCommandValidator()
{
RuleFor(command => command.PatientId).GreaterThan(0);
RuleFor(command => command.WeightValue).InclusiveBetween(20, 200);
}
}
And this is called from my command like:
new AddWeightCommandValidator().ValidateAndThrow(request);
The problem is that the validation messages are still in English, not Dutch.
If I debug, right before the validator is called, the culture is correctly set to CurrentUICulture and CurrentCulture.
Does anyone have an idea what I am doing wrong?
source to share
Thanks to Stijn's tip, I started looking at how I can use my own resources for Fluent Validation, and that's how I did it.
The culture is set in global.asax, and the resource provider type for Fluent Validation is set based on that culture:
protected void Application_PostAuthenticateRequest()
{
// Set culture
var culture = CultureInfo.CreateSpecificCulture("nl-BE");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
// Set Fluent Validation resource based on culture
switch (Thread.CurrentThread.CurrentUICulture.ToString())
{
case "nl-BE":
ValidatorOptions.ResourceProviderType = typeof(Prim.Mgp.Infrastructure.Resources.nl_BE);
break;
}
}
Fluent Validation will then look for translations in the corresponding resource file.
Resource files are located in a separate project. Here all Fluent Validation keys are defined, like inclusivebetween_error etc. In addition, various properties are defined here, such as WeightValue.
Finally, the WithLocalizedName validator is used to localize property names:
RuleFor(command => command.WeightValue).InclusiveBetween(20, 200).WithLocalizedName(() => Prim.Mgp.Infrastructure.Resources.nl_BE.WeightValue);
source to share