![](/img/trans.png)
[英]ASP.NET Core Error Handling with RouteDataRequestCultureProvider
[英]How to use RouteDataRequestCultureProvider with ASP.NET Core 2.2 EndpointRouting enabled?
我正在嘗試在新的 ASP.NET Core 2.2 MVC 項目中使用RouteDataRequestCultureProvider
。
我已閱讀有關ASP.NET Core 中路由的 Microsoft 文檔以了解 2.2 中引入的更改,但我不明白為什么“文化”不被識別為 URL 生成的環境值。
我更新了 Startup.cs 中的ConfigureServices
以包含設置:
var supportedCultres = new[] { new CultureInfo("en"), new CultureInfo("fr") };
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en");
options.SupportedCultures = supportedCultres;
options.SupportedUICultures = supportedCultres;
options.RequestCultureProviders = new[] { new RouteDataRequestCultureProvider { Options = options } };
});
我修改了Configure
的應用程序和默認路由以使用“文化”路徑段:
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
app.UseRequestLocalization(locOptions);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{culture:regex(^(en|fr)$)}/{controller=Home}/{action=Index}/{id?}");
});
當我按預期導航到 /en 或 /fr 時,此路由將解析為HomeController.Index()
,但使用 Anchor Tag Helper 指向其他操作的任何鏈接都將呈現為<a href="">
(包括生成的隱私鏈接)由腳手架)。
關閉 EnableEndpointRouting 會導致 Anchor Tag Helper 再次工作:
services.AddMvc(opts => { opts.EnableEndpointRouting = false; })
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
添加顯式asp-route-culture
值也有效:
<a asp-route-culture="en" asp-controller="Home" asp-action="About">About</a>
但我不明白為什么需要進行任何更改,因為“文化”路由值已經存在於RouteData.Values
集合中,並且錨標記助手會自動使用以前的路由模型。 這些是有效的操作路由,那么當路由包含文化時,為什么 URL 生成失敗?
我在使用 net core 3.1 時遇到了同樣的問題。 我最終設法找到了原因並找到了解決方案。
TLDNR:由於核心 2.2 環境路由值不再傳遞到 url 構建器,您需要顯式傳遞它們。我通過擴展 razor 錨標記助手解決了這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.