【发布时间】:2021-01-03 01:11:59
【问题描述】:
我正在开发一个包含多语言内容的 ASP.NET CORE 应用程序。文化正在成功改变,也可以在应用程序 cookie 中查看。
但 URL 不会因语言切换而改变。 我在启动时尝试过的如下:
启动 ConfigureServices:
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
options => { options.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(ShareResource));
});
启动配置:
var supportedCultures = new List<CultureInfo>()
{
new CultureInfo("en"),
new CultureInfo("de"),
new CultureInfo("fr"),
new CultureInfo("pt"),
new CultureInfo("tr")
};
var options = new RequestLocalizationOptions()
{
DefaultRequestCulture = new RequestCulture("en"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures,
RequestCultureProviders = new List<IRequestCultureProvider>()
{
new QueryStringRequestCultureProvider(),
new CookieRequestCultureProvider()
}
};
app.UseRequestLocalization(options);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "defaultWithLang",
pattern: "{lang}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
在HomeController中:
public IActionResult ChangeLang(string lang)
{
Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(lang)),
new CookieOptions(){
Expires = DateTimeOffset.UtcNow.AddYears(1)
});
return Redirect(Request.Headers["Referer"].ToString());
}
我希望显示的 URL 类似于“http://domain/en/controller/action”,但它不会通过切换语言而改变,并且始终类似于没有语言的“http://domain/controller/action”代码。
还有什么我必须在启动时或其他地方添加到我的代码中的吗? 感谢您提供任何帮助。
【问题讨论】:
-
手动设置 url 会发生什么?
-
@DervişKayımbaşıoğlu,没什么!实际上两个 URL 之间没有区别(有和没有语言代码)!
标签: c# asp.net-mvc asp.net-core