【发布时间】:2020-02-25 15:21:01
【问题描述】:
最近我开始使用 RazorPages。 (3.1)
在我的cshtml中,当我使用时:
<a asp-page="/Index">
生成的 HTML 是:
<a href="/">
干净整洁。
当我引入自定义 PageRouteModelConvention(用于文化)和自定义 AnchorTagHelper 时,它不再以这种方式运行。
只要我的 URL 以文化 (domain.com/nl-BE/) 开头,主页的链接就会如下所示:
<a href="/nl-BE/Index">
虽然我想像以前一样在没有索引的情况下保留它
<a href="/nl-BE">
知道如何解决这个问题吗?
将我的文化添加到 url 的路由约定:
public class CultureTemplatePageRouteModelConvention : IPageRouteModelConvention
{
public void Apply(PageRouteModel model)
{
var selectorCount = model.Selectors.Count;
for (var i = 0; i < selectorCount; i++)
{
var selector = model.Selectors[i];
model.Selectors.Add(new SelectorModel
{
AttributeRouteModel = new AttributeRouteModel
{
Order = -1,
Template = AttributeRouteModel.CombineTemplates("{culture?}", selector.AttributeRouteModel.Template),
}
});
}
}
}
默认的anchortaghelper被替换为:
[HtmlTargetElement("a", Attributes = ActionAttributeName)]
[HtmlTargetElement("a", Attributes = ControllerAttributeName)]
[HtmlTargetElement("a", Attributes = AreaAttributeName)]
[HtmlTargetElement("a", Attributes = PageAttributeName)]
[HtmlTargetElement("a", Attributes = PageHandlerAttributeName)]
[HtmlTargetElement("a", Attributes = FragmentAttributeName)]
[HtmlTargetElement("a", Attributes = HostAttributeName)]
[HtmlTargetElement("a", Attributes = ProtocolAttributeName)]
[HtmlTargetElement("a", Attributes = RouteAttributeName)]
[HtmlTargetElement("a", Attributes = RouteValuesDictionaryName)]
[HtmlTargetElement("a", Attributes = RouteValuesPrefix + "*")]
public class CultureAnchorTagHelper : AnchorTagHelper
{
public CultureAnchorTagHelper(IHttpContextAccessor contextAccessor, IHtmlGenerator generator) :
base(generator)
{
this._contextAccessor = contextAccessor;
}
private const string ActionAttributeName = "asp-action";
private const string ControllerAttributeName = "asp-controller";
private const string AreaAttributeName = "asp-area";
private const string PageAttributeName = "asp-page";
private const string PageHandlerAttributeName = "asp-page-handler";
private const string FragmentAttributeName = "asp-fragment";
private const string HostAttributeName = "asp-host";
private const string ProtocolAttributeName = "asp-protocol";
private const string RouteAttributeName = "asp-route";
private const string RouteValuesDictionaryName = "asp-all-route-data";
private const string RouteValuesPrefix = "asp-route-";
private const string Href = "href";
private readonly IHttpContextAccessor _contextAccessor;
private readonly string defaultRequestCulture = "en";
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var culture = (string)_contextAccessor.HttpContext.Request.RouteValues["culture"];
if (culture != null && culture != defaultRequestCulture)
{
RouteValues["culture"] = culture;
}
base.Process(context, output);
}
}
【问题讨论】:
标签: asp.net-core routes localization razor-pages culture