我想在 AspCore Razor Page 中使用本地化。
但是,我遇到了以下错误:
CS0108: 'Pages_Index.ViewData' hides inherited member 'RazorPage<IndexModel>.ViewData'. Use the new keyword if hiding was intended.
CS0108: 'Pages_Index.Model' hides inherited member 'RazorPage<IndexModel>.Model'. Use the new keyword if hiding was intended.
CS0103: The name 'PageContext' does not exist in the current context.
The type 'Pages_Index' is not a valid page. A page must inherit from 'Microsoft.AspNetCore.Mvc.RazorPages.PageBase'
我的代码如下:
public abstract class BaseViewPage<TModel> : RazorPage<TModel>
{
[RazorInject]
public ILanguageService LanguageService { get; set; }
[RazorInject]
public ILocalizationService LocalizationService { get; set; }
public delegate HtmlString Localizer(string resourceKey, params object[] args);
private Localizer _localizer;
public Localizer Localize
{
get
{
//logic
return _localizer;
}
}
}
public abstract class CustomBaseViewPage : BaseViewPage<dynamic>
{ }
我在
@inherits CustomBaseViewPage<TModel>
中使用 _ViewImports.cshtml
。
查看代码为:
@{
ViewData["Title"] = Localize("customer.page.create.title");
}
<div>
<h3>@Localize("customer.page.create.title")</h3>
</div>
首先,如果除了本地化之外没有更多关于
CustomBaseViewPage
的内容,那么这应该不是必需的,而是您应该在要本地化的每个视图中注入 IStringLocalizer
。
尽管如此,您也可以使用自定义基类,但必须删除所有页面中的
@page
指令,以免存在多个包含相同成员的基类。另外,您还必须处理路由,请参阅 https://learn.microsoft.com/en-us/aspnet/core/razor-pages/razor-pages-conventions?view=aspnetcore-8.0