Localizing an ASP.Net Core web application with one resource file (per language) is not as easy as I have thought. So here I am sharing a straight forward and easy way to do just that in less than 5 minutes.
This post was tested in ASP.Net Core 2.1.
First let’s understand the tree main points that need to be localized in an ASP.Net Core application.
- Data annotation localization
- Controllers localization
- View localization
All these aspects need to be modified.
First let’s create the required files (paths and namespaces should be as described):
We need a Resources folder in the project root
Then create resource files in this folder, here is a list of my files:
Now create an empty class called SharedResources in the root of the project and with the namespace of the project.
You’re now ready to start configuring the localization!
Data annotation localization
Create an anonymous provider using the empty class from earlier
This part is for Controllers or any code that would usually use the IStringLocalizer.
Request the IStringLocalizer from the DI with the SharedResources class.
Here you need to create your own implementation of a Localizer and put this class in the Resources folder.
I just created a very trivial localizer that uses the IStringLocalizer behind the scenes (This obviously can be improved).
Then inject this Localizer instead of the default IViewLocalizer.
In my case I injected the SharedViewLocalizer in the _ViewImports and named the instance as Localizer. This way I only had to modify one file to update all the views in the project.
That’s it! You’ve localized your ASP.Net Core application in less than 5 minutes and you now only have one resource file to maintain.