private ICultureExpression ExtractLanguageFromHeader(HttpContext context, ICultureContext cultureContext) { ICultureOption cultureOption = cultureContext.CultureOption; StringValues languageValues; if (!context.Request.Headers.TryGetValue("Accept-Language", out languageValues)) { return(null); } List <string> languageCodes = new List <string>(); foreach (string lang in languageValues) { languageCodes.AddRange(lang.Split(';').Select(x => x.ToLower())); } ICultureExpression expression; foreach (string lang in languageCodes) { if (lang.TryParseCultureExpression(out expression)) { if (checkCultureSupported && !cultureContext.CultureOption.IsCultureSupported(expression)) { return(null); } return(expression); } } return(null); }
public static IServiceCollection AddMvcLocalization( this IServiceCollection services, string defaultCulture, IEnumerable <string> supportedCultures, int culturePageCacheSize = 100, int cultureCacheSize = 20) { services.AddSingleton <ICultureOption>(new CultureOption(defaultCulture, supportedCultures)); services.AddSingleton <ICultureFileCache>(provider => { IHostingEnvironment env = provider.GetRequiredService <IHostingEnvironment>(); ICultureOption cultureOption = provider.GetRequiredService <ICultureOption>(); return(new CultureFileCache(env, cultureOption, cultureCacheSize, culturePageCacheSize)); }); services.AddSingleton <ICultureFileCollectionCache>(provider => { IHostingEnvironment env = provider.GetRequiredService <IHostingEnvironment>(); return(new CultureFileCollectionCache(env, cultureCacheSize, culturePageCacheSize)); }); services.AddScoped <ICultureContext, CultureContext>(); services.AddSingleton <CultureMatchingViewResultExecutor>(); services.AddScoped <ILocalizedViewRenderContextAccessor, LocalizedViewRenderContextAccessor>(); services.AddScoped <ILocalizedViewRenderContext>(service => { ILocalizedViewRenderContextAccessor accessor = service.GetRequiredService <ILocalizedViewRenderContextAccessor>(); if (accessor.Context == null) { ICultureContext cultureContext = service.GetRequiredService <ICultureContext>(); accessor.Context = new LocalizedViewRenderContext(cultureContext.CurrentCulture, cultureContext.CurrentCulture, cultureContext.UrlCultureSpecifier); } return(accessor.Context); }); return(services); }
private ICultureExpression ExtractLanguageFromUrl(HttpContext context, ICultureContext cultureContext, out string urlSpecifier, out string action) { ICultureOption cultureOption = cultureContext.CultureOption; string path = context.Request.Path.Value; if (UrlComponents.TryParse(path, out UrlComponents urlComponents)) { action = urlComponents.Action; context.Request.Path = new PathString(action); urlSpecifier = urlComponents.CultureSpecifier ?? ""; if (urlSpecifier.Length > 0) { context.Request.PathBase = context.Request.PathBase.Add(new PathString(urlSpecifier)); } if (urlComponents.Culture != null && checkCultureSupported && !cultureContext.CultureOption.IsCultureSupported(urlComponents.Culture)) { return(null); } return(urlComponents.Culture); } else { urlSpecifier = ""; action = path; return(null); } }
public SiteMapNodeHelper( ISiteMap siteMap, ICultureContext cultureContext, ISiteMapNodeCreatorFactory siteMapNodeCreatorFactory, IDynamicSiteMapNodeBuilderFactory dynamicSiteMapNodeBuilderFactory, IReservedAttributeNameProvider reservedAttributeNameProvider, ICultureContextFactory cultureContextFactory ) { if (siteMap == null) throw new ArgumentNullException("siteMap"); if (cultureContext == null) throw new ArgumentNullException("cultureContext"); if (siteMapNodeCreatorFactory == null) throw new ArgumentNullException("siteMapNodeCreatorFactory"); if (dynamicSiteMapNodeBuilderFactory == null) throw new ArgumentNullException("dynamicSiteMapNodeBuilderFactory"); if (reservedAttributeNameProvider == null) throw new ArgumentNullException("reservedAttributeNameProvider"); if (cultureContextFactory == null) throw new ArgumentNullException("cultureContextFactory"); this.siteMap = siteMap; this.cultureContext = cultureContext; this.siteMapNodeCreatorFactory = siteMapNodeCreatorFactory; this.dynamicSiteMapNodeBuilderFactory = dynamicSiteMapNodeBuilderFactory; this.reservedAttributeNameProvider = reservedAttributeNameProvider; this.cultureContextFactory = cultureContextFactory; }
public static string Match(this ICodeMatchingService service, string code, string defaultName) { HttpContext httpContext = service.HttpContext; IServiceProvider services = httpContext.RequestServices; ICultureOption cultureOption = services.GetRequiredService <ICultureOption>(); ICultureContext cultureContext = services.GetRequiredService <ICultureContext>(); return(service.Match(cultureContext.CurrentCulture, cultureOption.DefaultCulture, code, defaultName)); }
public static void Match <T>(this ICodeMatchingService service, IEnumerable <T> codedItems) where T : ICodedItem { HttpContext httpContext = service.HttpContext; IServiceProvider services = httpContext.RequestServices; ICultureOption cultureOption = services.GetRequiredService <ICultureOption>(); ICultureContext cultureContext = services.GetRequiredService <ICultureContext>(); service.Match(cultureContext.CurrentCulture, cultureOption.DefaultCulture, codedItems); }
public ISiteMapNodeHelper Create(ISiteMap siteMap, ICultureContext cultureContext) { return new SiteMapNodeHelper( siteMap, cultureContext, this.siteMapNodeCreatorFactory, this.dynamicSiteMapNodeBuilderFactory, this.reservedAttributeNameProvider, this.cultureContextFactory); }
public ISiteMapNodeHelper Create(ISiteMap siteMap, ICultureContext cultureContext) { return(new SiteMapNodeHelper( siteMap, cultureContext, this.siteMapNodeCreatorFactory, this.dynamicSiteMapNodeBuilderFactory, this.reservedAttributeNameProvider, this.cultureContextFactory)); }
public override ViewResult View(string viewName, object model) { ViewData.Model = model; ICultureContext cultureContext = HttpContext.RequestServices.GetRequiredService <ICultureContext>(); return(new CultureMatchingViewResult(cultureContext.CurrentCulture) { ViewData = ViewData, TempData = TempData, ViewName = viewName }); }
public override async Task ExecuteResultAsync(ActionContext context) { if (!(context is PageContext pageContext)) { throw new ArgumentException($"{nameof(context)} should be instance of type {typeof(PageContext).Name}"); } string executingFilePath = "."; string basePath = this.Page.Path; string fileName = Path.GetFileName(basePath); string pageName = Path.GetFileNameWithoutExtension(basePath); string directory = basePath.Substring(0, basePath.Length - fileName.Length); while (directory[directory.Length - 1] == '/') { directory = directory.Substring(0, directory.Length - 1); } HttpContext httpContext = pageContext.HttpContext; IRazorViewEngine engine = httpContext.RequestServices.GetRequiredService <IRazorViewEngine>(); ICultureContext cultureContext = httpContext.RequestServices.GetRequiredService <ICultureContext>(); IFileCultureInfo fileCultureInfo = httpContext.RequestServices.GetRequiredService <ICultureFileCache>().Get(_requestedCulture, directory, pageName, "cshtml"); if (fileCultureInfo != null) { httpContext.RequestServices.GetRequiredService <ILocalizedViewRenderContextAccessor>().Context = new LocalizedViewRenderContext(_requestedCulture, fileCultureInfo.Culture, cultureContext.UrlCultureSpecifier); string relativePath = fileCultureInfo.RelativePath; // 7 == ".cshtml".Length if (!relativePath.Equals(this.Page.Path)) { RazorPageResult pageResult = engine.GetPage(executingFilePath, relativePath); Page page = (Page)pageResult.Page; PageContext resultPageContext = pageContext.CreateCopy(); ViewContext resultViewContext = this.Page.ViewContext.CreateCopy(); page.ViewContext = resultViewContext; resultViewContext.ExecutingFilePath = relativePath; resultPageContext.ActionDescriptor.PageTypeInfo = page.GetType().GetTypeInfo(); resultPageContext.ActionDescriptor.RelativePath = relativePath; page.PageContext = resultPageContext; page.HtmlEncoder = this.Page.HtmlEncoder; page.Path = relativePath; this.Page = page; } } else { httpContext.RequestServices.GetRequiredService <ILocalizedViewRenderContextAccessor>().Context = new LocalizedViewRenderContext(_requestedCulture, null, cultureContext.UrlCultureSpecifier); } var executor = context.HttpContext.RequestServices.GetRequiredService <PageResultExecutor>(); await executor.ExecuteAsync(pageContext, this); }
private void InvokeMiddleware(HttpContext context, ICultureContext cultureContext) { ICultureExpression cultureExpression = ExtractLanguageFromUrl(context, cultureContext, out string urlSpecifier, out string action); cultureContext.UrlCultureSpecifier = urlSpecifier; if (cultureExpression == null) { cultureExpression = ExtractLanguageFromHeader(context, cultureContext); } if (cultureExpression == null) { cultureExpression = cultureContext.CultureOption.DefaultCulture; } cultureContext.Action = action; cultureContext.CurrentCulture = cultureExpression; }
public DynamicSiteMapNodeBuilder( ISiteMapNodeCreator siteMapNodeCreator, ICultureContext cultureContext, ICultureContextFactory cultureContextFactory ) { if (siteMapNodeCreator == null) throw new ArgumentNullException("siteMapNodeCreator"); if (cultureContext == null) throw new ArgumentNullException("cultureContext"); if (cultureContextFactory == null) throw new ArgumentNullException("cultureContextFactory"); this.siteMapNodeCreator = siteMapNodeCreator; this.cultureContext = cultureContext; this.cultureContextFactory = cultureContextFactory; }
public override ViewEngineResult FindView(ActionContext actionContext, ViewResult viewResult) { string viewName = viewResult.ViewName; if (viewName == null) { viewName = GetActionName(actionContext); } if (viewName == null) { return(base.FindView(actionContext, viewResult)); } string controllerName; if (!actionContext.ActionDescriptor.RouteValues.TryGetValue(ControllerNameKey, out controllerName) || string.IsNullOrEmpty(controllerName)) { controllerName = ""; } string directory = Path.Combine("Views", controllerName); HttpContext httpContext = actionContext.HttpContext; IServiceProvider provider = httpContext.RequestServices; ICultureOption cultureOption = provider.GetRequiredService <ICultureOption>(); ICultureContext cultureContext = provider.GetRequiredService <ICultureContext>(); CultureMatchingViewResult viewFindResult = (CultureMatchingViewResult)viewResult; ICultureFileCache fileCache = provider.GetRequiredService <ICultureFileCache>(); IFileCultureInfo fileCultureInfo = fileCache.Get(viewFindResult.RequestedCulture, directory, viewName, "cshtml"); if (fileCultureInfo != null) { httpContext.RequestServices.GetRequiredService <ILocalizedViewRenderContextAccessor>().Context = new LocalizedViewRenderContext(viewFindResult.RequestedCulture, fileCultureInfo.Culture, cultureContext.UrlCultureSpecifier); string relativePath = fileCultureInfo.RelativePath.Substring(0, fileCultureInfo.RelativePath.Length - 7); // 7 == ".cshtml".Length relativePath = relativePath.Substring(directory.Length + 1); viewResult.ViewName = relativePath; return(base.FindView(actionContext, viewResult)); } else { httpContext.RequestServices.GetRequiredService <ILocalizedViewRenderContextAccessor>().Context = new LocalizedViewRenderContext(viewFindResult.RequestedCulture, null, cultureContext.UrlCultureSpecifier); return(base.FindView(actionContext, viewResult)); } }
public SiteMapNodeHelper( ISiteMap siteMap, ICultureContext cultureContext, ISiteMapNodeCreatorFactory siteMapNodeCreatorFactory, IDynamicSiteMapNodeBuilderFactory dynamicSiteMapNodeBuilderFactory, IReservedAttributeNameProvider reservedAttributeNameProvider, ICultureContextFactory cultureContextFactory ) { if (siteMap == null) { throw new ArgumentNullException("siteMap"); } if (cultureContext == null) { throw new ArgumentNullException("cultureContext"); } if (siteMapNodeCreatorFactory == null) { throw new ArgumentNullException("siteMapNodeCreatorFactory"); } if (dynamicSiteMapNodeBuilderFactory == null) { throw new ArgumentNullException("dynamicSiteMapNodeBuilderFactory"); } if (reservedAttributeNameProvider == null) { throw new ArgumentNullException("reservedAttributeNameProvider"); } if (cultureContextFactory == null) { throw new ArgumentNullException("cultureContextFactory"); } this.siteMap = siteMap; this.cultureContext = cultureContext; this.siteMapNodeCreatorFactory = siteMapNodeCreatorFactory; this.dynamicSiteMapNodeBuilderFactory = dynamicSiteMapNodeBuilderFactory; this.reservedAttributeNameProvider = reservedAttributeNameProvider; this.cultureContextFactory = cultureContextFactory; }
public LocalizationCache([NotNull] ICultureStore store, [NotNull] IMemoryCache cache, [NotNull] ICultureContext context, [NotNull] ICultureManager manager, IOptionsSnapshot <CultureCacheOptions> optionsSnapshot) { _store = store ?? throw new ArgumentNullException(nameof(store)); _cache = cache ?? throw new ArgumentNullException(nameof(cache)); _manager = manager ?? throw new ArgumentNullException(nameof(manager)); _options = optionsSnapshot?.Value ?? new CultureCacheOptions(); _cacheOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromSeconds(_options.CacheLifespanInSeconds)) .RegisterPostEvictionCallback((key, value, reason, state) => { if (reason != EvictionReason.Replaced) { } }); _culture = context.UICulture; }
public DynamicSiteMapNodeBuilder( ISiteMapNodeCreator siteMapNodeCreator, ICultureContext cultureContext, ICultureContextFactory cultureContextFactory ) { if (siteMapNodeCreator == null) { throw new ArgumentNullException("siteMapNodeCreator"); } if (cultureContext == null) { throw new ArgumentNullException("cultureContext"); } if (cultureContextFactory == null) { throw new ArgumentNullException("cultureContextFactory"); } this.siteMapNodeCreator = siteMapNodeCreator; this.cultureContext = cultureContext; this.cultureContextFactory = cultureContextFactory; }
public Task Invoke(HttpContext context, ICultureContext cultureContext) { if (filter == null) { InvokeMiddleware(context, cultureContext); } else { UrlFilterResult filterResult = filter(context.Request.Path); if (filterResult is InvokeMiddlewareFilterResult) { InvokeMiddleware(context, cultureContext); } else if (filterResult is SetCultureFilterResult setCultureResult) { cultureContext.UrlCultureSpecifier = setCultureResult.CultureSpecifier; cultureContext.CurrentCulture = setCultureResult.Culture; cultureContext.Action = setCultureResult.Action; context.Request.Path = new PathString(cultureContext.Action); context.Request.PathBase = new PathString(setCultureResult.PathBase); } else if (filterResult is CheckHeaderFilterResult) { cultureContext.UrlCultureSpecifier = ""; ICultureExpression cultureExpression = ExtractLanguageFromHeader(context, cultureContext); if (cultureExpression == null) { cultureExpression = cultureContext.CultureOption.DefaultCulture; } cultureContext.Action = context.Request.Path; cultureContext.CurrentCulture = cultureExpression; } else { ICultureExpression cultureExpression = cultureContext.CultureOption.DefaultCulture; cultureContext.Action = context.Request.Path; cultureContext.CurrentCulture = cultureExpression; return(next(context)); } } string urlSpecifier = cultureContext.UrlCultureSpecifier; if (urlSpecifier.Length <= 0) { return(next(context)); } else { return(next(context).ContinueWith(tsk => { if ((context.Response.StatusCode == 301 || context.Response.StatusCode == 302) && context.Response.Headers.TryGetValue("Location", out StringValues locationValue) && locationValue.Count > 0) { string location = locationValue[0]; if (UrlComponents.TryParse(location, out UrlComponents urlComponents)) { if (urlComponents.IsRelative) { if (!string.IsNullOrEmpty(urlComponents.CultureSpecifier)) { // dose not change the location // context.Response.Headers["Location"] = urlSpecifier + context.Response.Headers["Location"]; return; } else { urlComponents.TrySetCulture(urlSpecifier); context.Response.Headers["Location"] = urlComponents.FullActionWithQuery; return; } } else { string host = context.Request.Host.Value; string requestedHost = urlComponents.FullHost; if (requestedHost != null && requestedHost.Equals(host, StringComparison.CurrentCultureIgnoreCase)) { if (!string.IsNullOrEmpty(urlComponents.CultureSpecifier)) { // dose not change the location // context.Response.Headers["Location"] = urlSpecifier + context.Response.Headers["Location"]; return; } else { urlComponents.TrySetCulture(urlSpecifier); context.Response.Headers["Location"] = urlComponents.FullActionWithQuery; return; } } else { // dose not change the location // context.Response.Headers["Location"] = urlSpecifier + context.Response.Headers["Location"]; return; } } } else { // dose not change the location // context.Response.Headers["Location"] = urlSpecifier + context.Response.Headers["Location"]; } } })); } }
public IDynamicSiteMapNodeBuilder Create(ISiteMap siteMap, ICultureContext cultureContext) { var siteMapNodeCreator = this.siteMapNodeCreatorFactory.Create(siteMap); return new DynamicSiteMapNodeBuilder(siteMapNodeCreator, cultureContext, this.cultureContextFactory); }
public IDynamicSiteMapNodeBuilder Create(ISiteMap siteMap, ICultureContext cultureContext) { var siteMapNodeCreator = this.siteMapNodeCreatorFactory.Create(siteMap); return(new DynamicSiteMapNodeBuilder(siteMapNodeCreator, cultureContext, this.cultureContextFactory)); }