.NET Core MVC手动本地化添加及语言切换失效问题
.NET Core MVC手动语言切换失效问题修复
问题描述
为.NET Core MVC应用添加保加利亚语(bg-BG)和英语(en-US)手动语言切换功能,已引入Microsoft.Localization NuGet包,创建了资源文件Resources/Views/Home/Landing.bg-BG.resx和Landing.en-US.resx,但切换语言并重定向到Landing页面时,页面语言无变化。
核心错误分析
- 重复调用
UseRequestLocalization覆盖配置:Program.cs中先后执行两次app.UseRequestLocalization(),第二次传入的空配置覆盖了之前已定义的支持文化、默认文化等关键设置,导致本地化逻辑无法识别Cookie中的语言选择。 - 未显式配置Cookie请求文化提供器:默认本地化配置不会优先读取Cookie中的语言设置,需手动添加并设置Cookie提供器的优先级。
修复步骤
1. 修正Program.cs的本地化中间件配置
删除重复的UseRequestLocalization调用,使用预配置的选项并添加Cookie请求文化提供器:
using Market.Services; using Market.Services.Firebase; using Market.Services.Inventory; using Market.Services.Offers; using Market.Services.Orders; using Market.Services.Reviews; using Microsoft.AspNetCore.Authentication.Cookies; using Market.Data; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Market.Data.Models; using Microsoft.AspNetCore.Builder; using Market.Services.Authentication; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Localization; using System.Globalization; using Microsoft.Extensions.Options; var cookiePolicyOptions = new CookiePolicyOptions { MinimumSameSitePolicy = SameSiteMode.Strict, }; var builder = WebApplication.CreateBuilder(args); // 添加控制器与视图服务,启用视图本地化 builder.Services.AddControllersWithViews() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); builder.Services.AddHttpClient(); // 配置Cookie认证 builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.ExpireTimeSpan = TimeSpan.FromMinutes(20); options.SlidingExpiration = true; options.AccessDeniedPath = "/Forbidden/"; }); // 配置本地化资源路径 builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); builder.Services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new[] { new CultureInfo("bg-BG"), new CultureInfo("en-US"), }; options.DefaultRequestCulture = new RequestCulture(culture: "bg-BG", uiCulture: "bg-BG"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; // 添加Cookie请求文化提供器,设置为最高优先级 options.RequestCultureProviders.Insert(0, new CookieRequestCultureProvider { CookieName = CookieRequestCultureProvider.DefaultCookieName, CookieOptions = new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(30), IsEssential = true, SameSite = SameSiteMode.Strict } }); }); builder.Services.AddHttpContextAccessor(); // 注册业务服务 builder.Services.AddScoped<IAuthenticationService, AuthenticationService>(); builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddScoped<IInventoryService, InventoryService>(); builder.Services.AddScoped<IOfferService, OfferService>(); builder.Services.AddScoped<IFirebaseServive, FirebaseService>(); builder.Services.AddScoped<IOrdersService, OrdersService>(); builder.Services.AddScoped<IReviewsService, ReviewsService>(); var app = builder.Build(); // 使用预配置的本地化选项,删除重复调用 var locOptions = app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>(); app.UseRequestLocalization(locOptions.Value); // 配置HTTP请求管道 if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(cookiePolicyOptions); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); // 默认路由配置 app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
2. 确认资源文件配置
- 确保资源文件路径与视图路径严格对应:视图
Views/Home/Landing.cshtml对应资源文件Resources/Views/Home/Landing.bg-BG.resx、Resources/Views/Home/Landing.en-US.resx - 右键资源文件→属性,设置生成操作为
嵌入的资源,自定义工具为ResXFileCodeGenerator
3. 验证视图的本地化调用
在Landing.cshtml中使用IViewLocalizer读取资源:
@inject IViewLocalizer Localizer <h1>@Localizer["Welcome"]</h1> <p>@Localizer["Description"]</p>
4. 优化SetLanguage方法的Cookie有效期
延长Cookie有效期,保证语言设置持久生效:
[HttpPost] public IActionResult SetLanguage(string culture, string returnUrl) { Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(30), IsEssential = true, SameSite = SameSiteMode.Strict } ); return LocalRedirect(returnUrl); }
验证步骤
- 启动应用,切换语言选择框选项
- 检查浏览器Cookie,确认存在
.AspNetCore.CultureCookie,值为c=bg-BG|uic=bg-BG或c=en-US|uic=en-US - 确认Landing页面文本已切换为对应语言
内容的提问来源于stack exchange,提问作者Gabriel Goranov
相关产品推荐
相关产品推荐

