作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试向我的 asp.net-core 项目添加多语言功能,但 RequestLocalization 中的 .net 3.1 和 5.0 之间有一些变化,我无法得到我想要的。我为每种语言添加了 Resource 文件,并在我的 razor 页面中使用了 Resource,它可以工作,但有一个不需要的默认路由错误,我希望我的路由对默认文化友好。
这就是我要的,
对于默认文化(土耳其语):
site.com/foo
site.com/foo/bar
site.com/foo/bar/5
对于非默认文化(英语):
site.com/en/foo
site.com/en/foo/bar
site.com/en/foo/bar/5
我的另一个问题是;我的项目将 site.com/foo/foo/bar 这个 url 呈现为 site.com/tr/foo/bar 这不好,我想它应该重定向到 404 页面。
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
services.AddLocalization(opts => opts.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("tr-TR"),
new CultureInfo("en")
};
options.DefaultRequestCulture = new RequestCulture("tr");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider());
});
services.AddControllersWithViews();
services.AddRazorPages();
services.AddRouting(options => options.LowercaseUrls = true);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
var supportedCultures = new string[] { "tr-TR", "en" };
app.UseRequestLocalization(options =>
options
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures)
.SetDefaultCulture("tr-TR")
.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context => Task.FromResult(new ProviderCultureResult("tr-TR"))))
);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "culture-route", pattern: "{culture}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(name: "default", "{culture=tr}/{controller=Home}/{action=Index}/{id?}");
});
}
Razor 资源使用和文化变化导航
最佳答案
为此,您需要在 ASP.Net Core 中配置稍微不同的本地化。
我创建了新的 ASP.Net Core MVC
项目并执行以下步骤:
UrlRequestCultureProvider
public class UrlRequestCultureProvider : RequestCultureProvider
{
private static readonly Regex PartLocalePattern = new Regex(@"^[a-z]{2}(-[a-z]{2,4})?$", RegexOptions.IgnoreCase);
private static readonly Regex FullLocalePattern = new Regex(@"^[a-z]{2}-[A-Z]{2}$", RegexOptions.IgnoreCase);
private static readonly Dictionary<string, string> LanguageMap = new Dictionary<string, string>
{
{ "en", "en-US" },
{ "fr", "fr-FR" }
};
public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var parts = httpContext.Request.Path.Value.Split('/');
// Get culture from path
var culture = parts[1];
if (parts.Length < 3)
{
return Task.FromResult<ProviderCultureResult>(null);
}
// For full languages fr-FR or en-US pattern
if (FullLocalePattern.IsMatch(culture))
{
return Task.FromResult(new ProviderCultureResult(culture));
}
// For part languages fr or en pattern
if (PartLocalePattern.IsMatch(culture))
{
var fullCulture = LanguageMap[culture];
return Task.FromResult(new ProviderCultureResult(fullCulture));
}
return Task.FromResult<ProviderCultureResult>(null);
}
}
ConfigureServices()
添加此代码: services.AddControllersWithViews().AddViewLocalization();
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCulters = new List<CultureInfo>()
{
new CultureInfo("en-US"),
new CultureInfo("fr-FR")
};
options.DefaultRequestCulture = new RequestCulture(supportedCulters.FirstOrDefault());
options.SupportedCultures = supportedCulters;
options.SupportedUICultures = supportedCulters;
options.RequestCultureProviders.Insert(0, new UrlRequestCultureProvider()
{
Options = options
});
});
Configure()
添加此代码: var requestLocalizationOptions = app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(requestLocalizationOptions.Value);
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "culture",
pattern: "{culture}/{controller=Home}/{action=Index}/{id?}");
});
Resources
用于 en-US 和 fr-FR 本地化。更多信息Resource file naming在 Microsoft 文档中。 Views.Home.Index.en-US.resx
Views.Home.Index.fr-FR.resx
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">@Localizer["Welcome"]</h1>
</div>
您可以在屏幕截图上看到结果。
关于c# - ASP.NET Core 5.0 RouteDataRequestCultureProvider 删除 url 中的默认文化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65789889/
我尝试向我的 asp.net-core 项目添加多语言功能,但 RequestLocalization 中的 .net 3.1 和 5.0 之间有一些变化,我无法得到我想要的。我为每种语言添加了 Re
我正在尝试使用RouteDataRequestCultureProvider在新的 ASP.NET Core 2.2 MVC 项目中。 我已阅读有关 Routing in ASP.NET Core 的
我是一名优秀的程序员,十分优秀!