在netcore中resource的配置及应用
1、创建resource资源文件
2、在容器中添加配置
1 builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); 2 builder.Services.Configure<RequestLocalizationOptions>(options => 3 { 4 var supportedCultures = new List<CultureInfo> 5 { 6 new CultureInfo("en"), 7 new CultureInfo("ja") 8 }; 9 options.DefaultRequestCulture = new RequestCulture(new CultureInfo("en")); 10 options.SupportedCultures = supportedCultures; 11 options.SupportedUICultures = supportedCultures; 12 options.AddInitialRequestCultureProvider(new CustomRequestCultureProvider(context => 13 { 14 var defaultLanguage = "ja";//"en"; 15 return Task.FromResult(new ProviderCultureResult(defaultLanguage, defaultLanguage))!; 16 })); 17 });resource configuration
1 var requestLocalizationOptions = app.Services.GetService<IOptions<RequestLocalizationOptions>>(); 2 app.UseRequestLocalization(requestLocalizationOptions!.Value);configuration pipeline
3、添加测试controller
1 [ApiExplorerSettings(GroupName = "demo2")] 2 [ApiController] 3 [Route("[controller]")] 4 public class ResourceController : Controller 5 { 6 private readonly IStringLocalizer<ResourceDemo> _localizer; 7 8 public ResourceController(IStringLocalizer<ResourceDemo> localizer) 9 { 10 _localizer = localizer; 11 } 12 13 [HttpGet("resourcedemo")] 14 public IActionResult ResourceDemo() 15 { 16 var value = _localizer.GetString("demo01"); 17 return new JsonResult(value); 18 } 19 }test controller
4、测试结果
资源文件内容,显示日语资源文件value是因为测试执行defaultlanguage 是 ja。
OK Resource 搞定!
标签:Resource,NetCore,localizer,defaultLanguage,Services,var,new,options From: https://www.cnblogs.com/qindy/p/17101061.html