In my previous articles, we covered the built-in validation for Minimal APIs, first the synchronous version in How to Validate Incoming Requests in .NET 10 Minimal APIs, and then the async one in Async Validation in .NET 11 Minimal APIs. Our validation rules are clean, our handlers are tidy, and our errors come back in a consistent format.
There's just one problem. All of those error messages are in English.
That's fine for many APIs, but if our API serves a frontend used in different countries, users expect to see validation errors in their own language. In .NET 10, getting there meant setting the ErrorMessageResourceType and ErrorMessageResourceName properties on every single attribute.
.NET 11 changes this by adding built-in localization to the validation pipeline. Error messages and display names are translated automatically, with no extra packages and no changes to our attributes.
In this article, we'll enable localization, select the language for each request, translate the built-in messages using convention-based keys, localize display names, and handle custom validation attributes. Then, we'll look at a few things you should keep in mind. As usual, we'll use our cat-themed API, and we'll translate it to Bulgarian.
Let's dive in!
Our Starting Point
We'll start with a version of the CreateCatRequest model we've used in the previous articles:
public record CreateCatRequest
{
[Required, Length(2, 25)]
public required string Name { get; init; }
[Required, Length(2, 20)]
public required string Breed { get; init; }
[Range(1, int.MaxValue)]
public required int AgeInMonths { get; init; }
}
And the familiar POST endpoint that accepts it:
var catRoutes = app.MapGroup("api/cats");
catRoutes.MapPost("", (CreateCatRequest request) =>
{
return TypedResults.Created($"/api/cats/{Random.Shared.Next(1, 999)}", request);
});
Of course, our Program class also has the AddValidation() call. If we send an invalid request, we get the English messages we already know:
{
"title": "One or more validation errors occurred.",
"errors": {
"Name": [
"The Name field is required."
],
"Breed": [
"The field Breed must be a string or collection type with a minimum length of '2' and maximum length of '20'."
]
}
}
Now, let's make these messages speak Bulgarian.
Enabling Localization for Validation
In .NET 11, there's no separate package or special opt-in call. Validation localization activates automatically when an IStringLocalizerFactory is available in the DI container. So, all we need is the standard AddLocalization() method:
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddValidation();
We call the AddLocalization() method, which registers the standard ASP.NET Core localization services, and we tell it that our resource files will live in a Resources folder. Then, we call AddValidation() as before.
Under the hood, the validation source generator now creates metadata that the localization pipeline uses. This is also why it only works for types the generator discovers, but we'll get to that later.
Selecting the Language for Each Request
The AddLocalization() method registers the localization services, but it doesn't decide which language a request should use. The validation pipeline looks up messages for the CultureInfo.CurrentUICulture, so we need something to set that for each request.
This is the job of the request localization middleware:
var app = builder.Build();
app.UseRequestLocalization(options => options
.SetDefaultCulture("en")
.AddSupportedCultures("en", "bg")
.AddSupportedUICultures("en", "bg"));
We call the UseRequestLocalization() method and configure two supported cultures, English and Bulgarian, with English as the default.
By default, the middleware checks the query string, a cookie, and the Accept-Language header, in that order. For an API, the Accept-Language header is usually what our clients send, so we'll use it in our examples.
If a client asks for a language we don't support, the middleware falls back to English. That's exactly what we want.
Translating the Built-In Messages
Now, we need the actual translations. This is where things get interesting.
When an attribute doesn't have an ErrorMessage set, the validation pipeline looks for a translation using conventional keys, from the most specific to the least specific:
{DeclaringType}_{MemberName}_{AttributeType}_Error{DeclaringType}_{AttributeType}_Error{AttributeType}_Error
For example, for the [Required] attribute on the Name property of our CreateCatRequest, the pipeline tries CreateCatRequest_Name_RequiredAttribute_Error, then CreateCatRequest_RequiredAttribute_Error, and finally RequiredAttribute_Error. If none of them exist, it falls back to the attribute's built-in English message.
This means we can translate the [Required] attribute for our whole model with a single RequiredAttribute_Error key. And we can still override the message for one specific property when we need to.
Creating the Resource File
By default, keys are resolved against the resources of the type that declares the member. Our CreateCatRequest lives in the root of the project, so we create a CreateCatRequest.bg.resx file in our Resources folder:
<data name="RequiredAttribute_Error" xml:space="preserve">
<value>Полето {0} е задължително.</value>
</data>
<data name="LengthAttribute_Error" xml:space="preserve">
<value>Полето {0} трябва да бъде между {1} и {2} символа.</value>
</data>
<data name="RangeAttribute_Error" xml:space="preserve">
<value>Полето {0} трябва да бъде между {1} и {2}.</value>
</data>
I'm only showing the data elements here. The rest of the file is the standard .resx boilerplate that Visual Studio or Rider generate for us.
The placeholders work just like in the default messages. {0} is always the display name of the property. The built-in attributes fill in their own values for the rest, so for [Length(2, 20)], {1} becomes 2 and {2} becomes 20.
Note that we don't need a neutral CreateCatRequest.resx file. When a key isn't found, the pipeline uses the built-in English message, so English keeps working as before.
Let's send a request in Bulgarian:
curl --location 'https://localhost:7298/api/cats' \
--header 'Content-Type: application/json' \
--header 'Accept-Language: bg' \
--data '{
"name": "",
"breed": "This is an extremely long and obscure cat breed",
"ageInMonths": 0
}'
And we get:
{
"title": "One or more validation errors occurred.",
"errors": {
"Name": [
"Полето Name е задължително."
],
"Breed": [
"Полето Breed трябва да бъде между 2 и 20 символа."
],
"AgeInMonths": [
"Полето AgeInMonths трябва да бъде между 1 и 2147483647."
]
}
}
The messages are translated, and we didn't touch a single attribute. But two things still look off. The property names in the messages are still in English, and so is the title. Let's fix the property names first.
Localizing Display Names
The {0} placeholder is filled with the display name of the property, which defaults to its name. To translate it, we use the [Display] attribute:
public record CreateCatRequest
{
[Display(Name = "Name")]
[Required, Length(2, 25)]
public required string Name { get; init; }
[Display(Name = "Breed")]
[Required, Length(2, 20)]
public required string Breed { get; init; }
[Display(Name = "Age in months")]
[Range(1, int.MaxValue)]
public required int AgeInMonths { get; init; }
}
The value of the Name property on the [Display] attribute is used as the resource key for the display name. Here, I use readable English names as keys. If a key isn't found, the value itself is used as the display name, so our English messages now say "Age in months" instead of "AgeInMonths", which is a nice bonus.
Then, we add the translations to our resource file:
<data name="Name" xml:space="preserve">
<value>Име</value>
</data>
<data name="Breed" xml:space="preserve">
<value>Порода</value>
</data>
<data name="Age in months" xml:space="preserve">
<value>Възраст в месеци</value>
</data>
Now, if we send the same request with the Accept-Language: bg header, we get:
{
"title": "One or more validation errors occurred.",
"errors": {
"Name": [
"Полето Име е задължително."
],
"Breed": [
"Полето Порода трябва да бъде между 2 и 20 символа."
],
"AgeInMonths": [
"Полето Възраст в месеци трябва да бъде между 1 и 2147483647."
]
}
}
Much better. Notice that the keys in the errors dictionary stay the same. They are property names, not display names, so our frontend can still map each error to the correct input field no matter the language.
If you are interested in having a deep dive into Minimal APIs, you can check my Minimal APIs in ASP.NET Core course here.
Using a Shared Resource File
One resource file per model works well for small APIs. But in a real application, we might have dozens of request models, and translating RequiredAttribute_Error in each of their resource files gets old quickly.
Instead, we can tell the validation pipeline to resolve all keys from a single shared resource file. First, we create an empty marker class:
public sealed class ValidationMessages;
Then, we rename our resource file to Resources/ValidationMessages.bg.resx, so it matches the marker class. Finally, we configure the LocalizerProvider option:
builder.Services.AddValidation(options =>
{
options.LocalizerProvider = (_, factory) => factory.Create(typeof(ValidationMessages));
});
The LocalizerProvider delegate receives the validated type and the IStringLocalizerFactory. We ignore the type and always create a localizer for our ValidationMessages marker class. The marker type identifies both the name of the resource file and the assembly that contains it.
Because the delegate receives the validated type, we can also mix both approaches. For example, we could use a shared file for most models and per-type files for a few special ones.
The convention-based keys work the same way with a shared file. We can still override a message for a single property with a more specific key, like CreateCatRequest_Name_RequiredAttribute_Error.
Localizing Custom Validation Attributes
Built-in attributes know how to fill in their own placeholders. But what about our own attributes?
Let's say we want a cat-specific rule. No cat in our system can be older than 240 months:
public sealed class MaxCatAgeAttribute : ValidationAttribute
{
public MaxCatAgeAttribute(int months)
{
Months = months;
ErrorMessage = "{0} can't be more than {1} months.";
}
public int Months { get; }
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value is int ageInMonths && ageInMonths > Months)
{
return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName),
[validationContext.MemberName!]);
}
return ValidationResult.Success;
}
public override string FormatMessage(string format, string name) =>
string.Format(CultureInfo.CurrentCulture, format, name, Months);
}
There are two important parts here.
First, we set the ErrorMessage property in the constructor. When ErrorMessage is set, its value becomes the lookup key, and it takes precedence over the conventional keys. So our English message is both the fallback and the key we'll use in the resource file.
Second, we override the new virtual FormatMessage() method that .NET 11 adds to the ValidationAttribute base class. It receives a message template and the display name, and returns the final message. This is exactly how the built-in [Length] and [Range] attributes fill in their {1} and {2} placeholders. The validation pipeline calls it with the localized template and the localized display name, so all we have to do is fill in our own placeholder, {1}, with the Months value.
Note that we don't override the FormatErrorMessage() method. Its default implementation calls FormatMessage() with the English ErrorMessage template, so the non-localized path works without any extra code.
Important: Some early .NET 11 documentation describes an IValidationMessageFormatter interface for this. That interface isn't part of the GA release, so if you run into it, override FormatMessage() instead.
Now, we apply our attribute:
[Display(Name = "Age in months")]
[Range(1, int.MaxValue), MaxCatAge(240)]
public required int AgeInMonths { get; init; }
And add the translation, using the English message as the key:
<data name="{0} can't be more than {1} months." xml:space="preserve">
<value>{0} не може да бъде повече от {1} месеца.</value>
</data>
Keys with spaces and placeholders look a bit unusual, but they're perfectly valid in .resx files.
Let's test it with a very old cat:
curl --location 'https://localhost:7298/api/cats' \
--header 'Content-Type: application/json' \
--header 'Accept-Language: bg' \
--data '{
"name": "Cody",
"breed": "Orange Tabby",
"ageInMonths": 300
}'
And we get:
{
"title": "One or more validation errors occurred.",
"errors": {
"AgeInMonths": [
"Възраст в месеци не може да бъде повече от 240 месеца."
]
}
}
Both the display name and our custom placeholder are filled in correctly.
The same rule applies to any existing ErrorMessage values. In my .NET 10 article, we had ErrorMessage = $"{nameof(Breed)} must be between 2 and 20 characters" on the Breed property. In .NET 11, that string becomes the lookup key, so to translate it, we add a resource entry with exactly that text as its name.
Translating the Problem Details Title
There's one English string left: "One or more validation errors occurred.". This title is part of the ProblemDetails response, not of the validation messages, so the validation pipeline doesn't touch it.
We can fix it with the IProblemDetailsService customization we already used to return 422 Unprocessable Entity responses:
builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = context =>
{
if (context.ProblemDetails is HttpValidationProblemDetails)
{
var localizer = context.HttpContext.RequestServices
.GetRequiredService<IStringLocalizer<ValidationMessages>>();
context.ProblemDetails.Title = localizer["One or more validation errors occurred."];
}
};
});
Inside the CustomizeProblemDetails callback, we check if we're dealing with a validation problem. If so, we resolve an IStringLocalizer<ValidationMessages> from the request services and replace the title with its translation. Again, we use the English text as the key, so English requests get the original title.
Then, we add the translation to our resource file:
<data name="One or more validation errors occurred." xml:space="preserve">
<value>Възникнаха една или повече грешки при валидацията.</value>
</data>
Now, our whole validation response is in Bulgarian.
Things to Watch Out For
Localization is easy to set up, but it's also easy to break silently. Here are a few things I'd keep in mind.
Missing Translations Fail Silently
If a key doesn't resolve, the pipeline falls back to the built-in English message. There's no exception and no log entry. This is great for our users, as they never see a raw resource key, but it also means a typo in a key goes unnoticed. I recommend adding a few integration tests that send requests with an Accept-Language header and assert on the translated messages.
Project Names With Dashes Break Resource Lookup
This one is easy to miss. If your project name contains dashes, like Cat-Api, nothing gets translated, not even strings you read through IStringLocalizer directly.
The reason is that the compiler embeds resources using the project's root namespace, where dashes are replaced with underscores, so we get Cat_Api.Resources.ValidationMessages.bg. But the localizer factory builds the resource name from the assembly name, which still has the dashes: Cat-Api.Resources.ValidationMessages. The names don't match, so the lookup silently fails and we get English everywhere.
The fix is a single line in our Program class:
[assembly: RootNamespace("Cat_Api")]
The RootNamespaceAttribute from the Microsoft.Extensions.Localization namespace tells the factory which root namespace to use. If your project name has no dashes, you don't need it.
Resource Files Must Live in the Right Project
For per-type lookup, resource files have to live in the project that declares the validated type. If your request models live in a class library, so do their resource files. A shared resource file referenced through a marker type in your API project is a good alternative in that case.
Attributes That Localize Themselves Are Skipped
Attributes that use ErrorMessageResourceType perform their own resource lookup, just like in .NET 10. The new pipeline doesn't process them. This means you can migrate gradually, but it also means you shouldn't mix both approaches on the same attribute and expect the new conventions to kick in.
Your Types Must Be Discoverable
Localization relies on the metadata created by the validation source generator. If AddValidation() isn't called from the assembly that declares your models, you won't get any validation, let alone localized messages. The same rules I described in my async validation article apply here as well.
Conclusion
With .NET 11, localizing validation messages in Minimal APIs no longer means decorating every attribute with resource types and names. We register localization, select the culture per request, and the validation pipeline translates messages and display names for us.
Conventional keys let us translate a whole attribute type with a single resource entry, while more specific keys and ErrorMessage values give us full control when we need it. And with the new FormatMessage() override, our custom attributes can be localized just as easily as the built-in ones.
Frequently Asked Questions
Do I need an extra NuGet package to localize validation messages?
No. Calling AddLocalization() together with AddValidation() is enough. Localization activates automatically when an IStringLocalizerFactory is registered.
Where does the validation pipeline get the current language from?
From CultureInfo.CurrentUICulture. In ASP.NET Core, the request localization middleware sets it for each request, for example, based on the Accept-Language header.
Do I need a neutral .resx file for English?
No. If a key isn't found, the attribute's built-in message is used, so you only need resource files for the languages you translate to.
Can I store translations in a database instead of .resx files?
Yes. Register your own IStringLocalizerFactory implementation, and it takes precedence over the default resource file implementation.
Do the keys in the errors dictionary get translated?
No. They are property names, not display names, so clients can map errors to fields regardless of the language.
Does validation localization work in Blazor as well?
Yes. The same Microsoft.Extensions.Validation pipeline powers Blazor form validation, so a message localizes identically in a Minimal API endpoint and in a Blazor form.