RazorPage .NET 5 如何自定义本地化提供程序.resx 到数据库

问题描述

我正在将 ASP.NET Webform .net 4.8 迁移到 RazorPage .Net5。

在我的 asp.net webform 网站中,我已将翻译部分驱逐到数据库而不是 .resx 文件

我继承了以下类:ResourceProviderFactory、IResourceProvider 和 ExpressionBuilder

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

允许保留 asp.net 语法

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

必须使用 razop 页面

@inject IViewLocalizer Localizer
@Localizer["MyDescription"]

并配置服务

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

如何更改本地化服务的认行为,您应该从哪个类继承以及如何注入这个新类以便使用这个新的数据库提供程序加载资源?

解决方法

我实施了解决方案,方法如下。

创建实现 IStringLocalizer 和 IStringLocalizerFactory 的类

在网站启动时

添加:

services.AddRazorPages().AddViewLocalization();

services.AddSingleton<IStringLocalizerFactory,SqlStringLocalizerFactory>();

进入剃刀页面使用

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

如果你想在你的 c# 代码中获取值,你可以注入一个 IStringLocalizer 但如果你的资源是 html 你必须使用 IHtmlLocalizer