ASP.NET Core supports culture based views for more complex localizations. It means we have one view per culture per controller action. This blog post shows how to use culture based views in ASP.NET Core and how to implement them.
Sample solution. Working code introduced here and in my blog post ASP.NET Core: Simple localization and language based URL-s is available in GitHub repository gpeipman/AspNetCoreLocalization.
Adding culture based views
Culture based views can be organized in views folder two ways:
- using subfolders – controller views folder has subfolders named by culture and each of these folders contains views for given culture,
- using culture suffix – culture is specified in the end of view name, just before file extensions.
The screen fragment on right shows how Contacts view has both localizations applied. For Estonian culture (et) there is subfolder and for Russian culture (ru) the culture is specifien in view name. For all other cases fallback to Contacts.cshtml is made.
Enabling view localization
Before creating views we need to add support for culture based views. For this we call AddViewLocalization() method on IMvcBuilder (it is not defined for services collection). If you are not using Microsoft.AspNetCore.All package then add NuGet reference to Microsoft.AspNetCore.Mvc.Localization package. The following code fragment comes from ConfigureServices() method of sample solution Startup class.
options.DataAnnotationLocalizerProvider = (type, factory) =>
Notice LanguageViewLocalizationExpanderFormat enum and how we use it here to support views in culture based subfolders and views that have culture in their name. This is all I had to do to enable support for culture based views in sample solution.
Culture based views are useful with more complex localization cases. Once localization is set up for web application it is easy to add support for culture based views. All we had to do was creating views using culture named folders or culture based view names and adding line of code to application start-up to notify ASP.NET Core that we use this feature.