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

RazorPage .NET 5 how to customize localization provider (.resx to database)

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

在我的 asp.net 网络表单网站中,我将翻译部分导出到数据库而不是 .resx 文件。

我继承自以下 classes: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();
}

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

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

创建 类 实现 IStringLocalizer 和 IStringLocalizerFactory

在站点的启动中

添加:

services.AddRazorPages().AddViewLocalization();

services.AddSingleton<IStringLocalizerFactory, SqlStringLocalizerFactory>();

进入razor页面使用

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

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