1.添加资源文件
2.program添加多语言配置,默认语言为中文
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLocalization();
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("zh"),
new CultureInfo("en"),
new CultureInfo("th"),
new CultureInfo("vi")
};
options.DefaultRequestCulture = new RequestCulture(new CultureInfo("zh"));
foreach(var culture in supportedCultures)
{
culture.DateTimeFormat = new CultureInfo("zh").DateTimeFormat;
}
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.AddInitialRequestCultureProvider(new AcceptLanguageHeaderRequestCultureProvider());
});
var app = builder.Build();
var requestLocalizationOptions = app.Services.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(requestLocalizationOptions!.Value);
3.可以通过AcceptLanguageHeaderRequestCultureProvider在header传参accept-language,接口可通过获取accept-language的值来切换返回的语言
4.切换成其他语言时,如何使用国内的时区?比如切换成泰语时,时间会按照泰国的佛历显示,要切换成国内的时区就需要处理对应语言的DateTimeFormat,如果需要按照对应时区显示时间,可去掉该代码
5.controller中使用,service使用与controller一样
public class DemoController : ControllerBase{
IStringLocalizer<LanguageResources> _stringLocalizer;
public DemoController(IStringLocalizer<LanguageResources> stringLocalizer){
_stringLocalizer = stringLocalizer;
}
public string Test(){
return _stringLocalizer["HelloWorld"].Value;
}
}