.Net Core 多语言,可以通过如下Action改变当前语言,lang可以是“en”,"zh-CHS" 等
[AllowAnonymous] public IActionResult SetLang(string lang, string returnUrl = "/") { Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, //默认 Cookie 名称是:.AspNetCore.Culture CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(lang)) ); return LocalRedirect(returnUrl); }
但是,保存当前语言的Cookie的名称是 CookieRequestCultureProvider.DefaultCookieName,这是一个只读静态变量,默认值是 “.AspNetCore.Culture”。不想用这个Cookie名称,想改成类似“MyApp.Culture”名称。能做到吗?
参考 How to get CookieName used in CookieRequestCultureProvider? 中的回答:
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
// Find the cookie provider with LINQ
var cookieProvider = options.Value.RequestCultureProviders
.OfType<CookieRequestCultureProvider>()
.First();
// Set the new cookie name
cookieProvider.CookieName = "NEW-NAME";
app.UseRequestLocalization(options.Value);
果然可以了👍
Response.Cookies.Append("MyApp.Culture", CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(lang)));
关键是这里 app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>(),厉害了 dudu