在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
在Startup public void ConfigureServices(IServiceCollection services) { services.AddLocalization(); services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new List<CultureInfo> { new CultureInfo("en-us"), new CultureInfo("zh-cn") }; options.DefaultRequestCulture = new RequestCulture(culture: "en-us", uiCulture: "en-us"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; options.RequestCultureProviders = new IRequestCultureProvider[] { new RouteDataRequestCultureProvider { IndexOfCulture = 1, IndexofUiCulture = 1 } }; }); services.Configure<RouteOptions>(options => { options.ConstraintMap.Add("culture", typeof(LanguageRouteConstraint)); }); services.AddControllers(); } 在Startup.cs类的 var localizeOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>(); app.UseRequestLocalization(localizeOptions.Value);
ASP.NET Core 本地化默认向我们提供了四个方式,可用于确定正在执行的请求的当前区域性:
如下所示我将通过路由的方式,去确定当前区域 public class RouteDataRequestCultureProvider : RequestCultureProvider { public int IndexOfCulture; public int IndexofUiCulture; public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext) { if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); string uiCulture; string culture = uiCulture = httpContext.Request.Path.Value.Split('/')[IndexOfCulture]; var providerResultCulture = new ProviderCultureResult(culture, uiCulture); return Task.FromResult(providerResultCulture); } } 通过如下代码片段实现 public class LanguageRouteConstraint : IRouteConstraint { public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { if (!values.ContainsKey("culture")) return false; var culture = values["culture"].ToString(); return culture == "en-us" || culture == "zh-cn"; } } 添加区域资源文件 注入 [Route("{culture:culture}/[controller]")] [ApiController] public class HomeController : ControllerBase { private readonly IStringLocalizer<Resource> localizer; public HomeController(IStringLocalizer<Resource> localizer) { this.localizer = localizer; } public string Get() { return localizer["Home"]; } } 如下图所示 Reference https://github.com/hueifeng/BlogSample/tree/master/src/LocalizationSingleResx 到此这篇关于ASP.NET Core WebAPI实现本地化(单资源文件)的文章就介绍到这了,更多相关ASP.NET Core WebAPI本地化内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界! |
请发表评论