Localizing ASP.NET Core projects

A multilingual website allows your content to reach a wider audience. The Xperience ASP.NET Core integration builds upon services and middleware for localizing into different languages and cultures provided by the Core framework.

For localization to work, your project's middleware pipeline needs to register the system's request localization middleware. The middleware is registered as part of the UseKentico call. which should already be present in your application's pipeline. By default, the middleware ensures the correct culture for requests handled by the system (preview URLs, content tree-based routing, form and page builder features):

Application startup class
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	// Registers the localization middleware
    app.UseKentico();
    ...
}

Adding localization for custom routes

Request culture providers tell the framework where to search for the culture under which the current request should be served. For application-specific routes and features, you need to register and configure these providers accordingly.

Add culture providers via KenticoRequestLocalizationOptions – the class behaves identically to RequestLocalizationOptions provided by ASP.NET Core, but hides configuration handled for the Core application by Xperience. Such as the need to provide the list of supported application and UI cultures at compile-time – something that you control from the connected Xperience administration application.

For example, the following code snippet registers a RouteDataRequestCultureProvider that looks for the culture parameter in a request's "culture" route data parameter.

Application startup class
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<KenticoRequestLocalizationOptions>(options =>
    {
		// Registers a culture provider that sets request culture from the "culture" route data parameter
		// (e.g., for routes in the following format: {culture}/{controller}/{action})
        options.RequestCultureProviders.Add(new RouteDataRequestCultureProvider
        {
            RouteDataStringKey = "culture",
            UIRouteDataStringKey = "culture"
        });
    });

	...
}

Localizing site content

Individual text strings

Individual text strings displayed on the site (which are not stored within page fields) can be localized just like in any other ASP.NET Core application. Follow the practices described in Microsoft's localization documentation.

DataAnnotations localization

Similar to standalone text strings, the localization of data annotation attributes follows the conventional ASP.NET Core pattern. See the DataAnnotation localization section in the official ASP.NET Core documentation.

Pages in the content tree

Pages managed via a site's content tree are localized via the Pages application. When retrieving page content, load the correct culture version of pages based on the current culture of the request.

You can use the IPageRetriever API to automatically retrieve pages matching the culture of the current request. See Working with pages in the API.

Localizing page and form builder components

Builder components consist of multiple parts that all need to be localized if you wish to cover the whole interface. We recommend creating a separate resource file for each component.

Before you start localizing your component:

  1. Create a dedicated resource file.
    1. Create a dummy class that "wraps" the resource file and serves as its access point for the framework. The namespace of the class must correspond to its location on the file system minus its name. 

      // For example, for resource files located under ~/MyProject/ComponentResources/MyComponent, set MyProject.ComponentResources as the namespace
      namespace relative.path.to.file
      {		
      	// Dummy class for 'MyComponent.resx' or 'MyComponent.<culture code>.resx'
      	public class MyComponent
      	{
      	}
      }
    2. Create the corresponding resource file in the same folder as the dummy class. The resource file name needs to match the name of the class and contain the language code of the target culture in its suffix. For example: MyComponent.es-es.resx. For resource strings in the default culture, the suffix can be omitted.
      • If a corresponding .resx file is not found for the current culture, a fallback mechanism that attempts to find the closest matching culture takes over. See Culture fallback behavior in the ASP.NET Core documentation.
  2. Register the dummy class via the RegisterPageBuilderLocalizationResource attribute.
    • The registration makes all localization strings available client-side as well. This is required when localizing client-side resources of inline editors and modal dialogs.
    • Specify the type of the dummy class and the culture for which the resources are intended as the attribute's parameters.

      [assembly: RegisterPageBuilderLocalizationResource(typeof(MyComponent), "es-es")]

Now you can localize the component:

Component metadata

You can localize the displayed text of form builder components (form components, form builder sections, field validation rules, field visibility conditions) and page builder components (widgetspage builder sections, personalization condition types, page templates):

  1. Create resource strings containing the Display names and Descriptions of your components.

    • Use a unique prefix for the resource string key, for example, your company name. The prefix prevents possible conflicts with the resource strings of other components.

    • We recommend including the component's identifier as a part of the resource string key.

  2. Edit the class containing the given component's registration attribute and add {$key$} expressions into the string parameters of the attribute (such as name and description). Replace "key" with the key of the matching resource string.

    Example - Localizing a page builder section
    [assembly: RegisterSection("CompanyName.DefaultSection", "{$company.defaultsection.name$}", typeof(CustomSectionProperties), "~/Components/Sections/_MySection.cshtml", IconClass = "icon-paragraph", Description = "{$company.defaultsection.description$}")]

Partial views of inline property editors

You can localize strings in partial views that are only displayed in the administration interface. For example, the text of a widget property inline editor button:

  1. Create resource strings containing the Display names and Descriptions of your components.

    • Use a unique prefix for the resource string key, for example, your company name. The prefix prevents possible conflicts with the resource strings of other components.

    • We recommend including the component's identifier as a part of the resource string key.

  2. Localize the component's view using standard localization classes provided by the framework (IStringLocalizer, IHtmlLocalizer, IViewLocalizer).

Inline editor scripts

To localize strings in the client scripts of widget property inline editors:

  1. Create resource strings containing the Display names and Descriptions of your components.

    • Use a unique prefix for the resource string key, for example, your company name. The prefix prevents possible conflicts with the resource strings of other components.

    • We recommend including the component's identifier as a part of the resource string key.

  2. Access the registered resources via the localizationService property exposed by the options object provided by Xperience in the client-side init function.

    (function () {
      window.kentico.pageBuilder.registerInlineEditor("custom-editor", {
        init: function (options) {
            // Retrieves the localized text of the specified resource string (in the current user's preferred UI culture)
            var localizedString = options.localizationService.getString("resource.string.key");
     
     
            ...
        }
      });
    })();

After you localize component metadata, partial views and inline editor scripts, you can view the result in the Xperience administration interface. Change the UI language by opening the User menu and clicking on Change language. Navigate to a page where the page builder is initialized (in the Pages application) or the form builder (in the Forms application). Now text values in the user interface are displayed in the selected language.

Localizing text fields using macro expressions

If you need to supply a localized value into a field or text area where localization expressions are supported (such as the form builder UI), you can use expressions in the following formats:

Format

Description

Sample Value

Basic format:

{$key$}

Displays the value of the resource string with the specified key. Strings can be viewed and edited in the .resx files of your web projects.

{$myform.firstname$}

In-place localization:

{$=default_string|culture_code=translation|culture_code=translation|etc.$}

Displays the strings defined in the expression.


{$=Hello|de-de=Hallo|it-it=Ciao$}

See also: Macro syntax


Was this page helpful?