asp.net-core.net-corelocalizationrazor-pagesasp.net-core-5.0

How to customize localization provider (.resx to database) in Razor Pages


I am in the process of migrating an ASP.NET Web Form in .NET Framework 4.8 to a Razor Pages application in .NET 5

In my ASP.NET Web Forms website, I had deported the translation part to the database instead of a .resx file.

I had inherited from the following classes: ResourceProviderFactory, IResourceProvider and ExpressionBuilder,

<expressionBuilders>
   <remove expressionPrefix="Resources" />
   <!-- For Translator -->
   <add expressionPrefix="Resources" type="WebCore.Resource.SqlExpressionBuilder" />
</expressionBuilders>
<globalization uiCulture="auto" culture="auto" resourceProviderFactoryType="WebCore.Resource.SqlProviderFactory" />

which allowed me to keep the ASP.NET syntax:

<meta name="description" content="<%= GetLocalResourceObject("MetaDescription") %>" />

With Razor Pages you have to use"

@inject IViewLocalizer Localizer
@Localizer["MyDescription"]

And configure a service:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages().AddViewLocalization();
}

How can I change the default behavior of the localization service? Which class should I inherit from, and how do I inject this new class so that the resources are loaded with this new DB provider?


Solution

  • Create classes that implement IStringLocalizer and IStringLocalizerFactory. In the Startup.cs file for the site, add:

    services.AddRazorPages().AddViewLocalization();
    services.AddSingleton<IStringLocalizerFactory, SqlStringLocalizerFactory>();
    

    In the Razor Page, use:

    @using Microsoft.AspNetCore.Mvc.Localization
    @inject IViewLocalizer Localizer
    <h1>@Localizer["Title"]</h1>
    

    If you want to get the values in your C# code, you can inject IStringLocalizer<T>, but if your resource is in HTML, you must use IHtmlLocalizer<T>.