我想实现一种很好的本地化方法,需要帮助来弄清楚如何读出路由参数。首先,我实现了本地化,如下所示:
在 Startup.cs
中// Configure supported cultures and localization options
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("de-DE") };
options.DefaultRequestCulture = new RequestCulture("en-US", "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>
{
var cultureInfo = options.DefaultRequestCulture.Culture;
string contextRequestUrlPath = context.Request.Path.ToString();
foreach (var c in supportedCultures)
if (contextRequestUrlPath.Contains(c.ToString())) cultureInfo = c;
return Task.FromResult(new ProviderCultureResult(cultureInfo.ToString()));
}));
});
对于每个请求,我的 CustomRequestCultureProvider 通过string.Contains()检查文化信息是否在内部并更新 ProviderCultureResult 。
和iam一样路由:
app.UseMvc(
routes => { routes.MapRoute(name: "default", template: "{culture=en-US}/{controller=Home}/{action=Index}/{id?}"); });
有没有办法从当前路线读出文化模板元素?我需要在项目的几个点上检查这一点。另外在视图中我希望能够读出路由值而不是检查 context.Request.Path 字符串。
答案 0 :(得分:0)
尝试控制器中的任何位置:
var requestCultureFeature = HttpContext.Features.Get<IRequestCultureFeature>();
var culture = requestCultureFeature.RequestCulture.Culture;