环境 WIN10 VS2022 .NET8
1.👋创建项目
2.👀创建Resources Controllers
HomeController.en.resx
HomeController.fr.resx
HomeController.zh.resx
3.🌱Program.cs添加国际化支持
// 添加国际化支持
builder.Services.AddLocalization(options =>
{options.ResourcesPath = "Resources";
});var app = builder.Build();// 多语言
var supportedCultures = new List<CultureInfo>{new CultureInfo("en"),new CultureInfo("zh"),new CultureInfo("fr"),};app.UseRequestLocalization(new RequestLocalizationOptions
{DefaultRequestCulture = new RequestCulture("zh"),SupportedCultures = supportedCultures,SupportedUICultures = supportedCultures
});
4.⚡注入localizer
private readonly IStringLocalizer<HomeController> localizer;public HomeController(ILogger<HomeController> logger, IStringLocalizer<HomeController> localizer){_logger = logger;this.localizer = localizer;}
5.📫编写调用方法
[HttpGet]public ActionResult<string> Get(){string rsstr= localizer.GetString("String1").Value;//?ui-culture=zhreturn rsstr;}
默认是中文
?ui-culture=en 则取对应HomeController.en.resx 里面的String1
🐟参考:
ASP.NET MVC ベリーシンプル多言語対応2020 #C# - Qiita