StartUp.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "Localization", pattern: "{lang=cn}/{controller=Home}/{action=Index}/{id?}"); }); }
BaseController.cs 建个父类
public override void OnActionExecuting(ActionExecutingContext filterContext) { string defaultLang = "cn"; string cookieKey = "VipSoft.CurrentUICulture"; var lang = filterContext.RouteData.Values["lang"]; if (lang == null || string.IsNullOrWhiteSpace(lang.ToString())) { //如果URL中没有语言 看 Cookie 中有没有,都没有默认 en var cookie = filterContext.HttpContext.Request.Cookies[cookieKey]; if (cookie == null) { lang = defaultLang; } else { lang = cookie; } ///把语言值设置到路由值里 filterContext.RouteData.Values["lang"] = lang; } try { Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang.ToString()); } catch (Exception e) { Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(defaultLang); } CacheCenter.CurrentLang = Thread.CurrentThread.CurrentUICulture.Name == "en-US" ? "en" : defaultLang; /// 把设置保存进cookie CookieOptions cookieOptions = new CookieOptions(); cookieOptions.Expires = DateTime.Now.AddYears(1); filterContext.HttpContext.Response.Cookies.Append(cookieKey, Thread.CurrentThread.CurrentUICulture.Name, cookieOptions); base.OnActionExecuting(filterContext); }