/// <summary> /// Called before an action method executes. /// </summary> /// <param name="filterContext">The filter context.</param> public void OnActionExecuting(ActionExecutingContext filterContext) { var request = filterContext.HttpContext.Request; var values = filterContext.RouteData.Values; // Value is already injected from a route declaration if (values.ContainsKey("language")) { return; } // Value is part of the explicit route and is the preferred language (from those available) var preferred = _session.GetLanguageFromSessionOrService(filterContext.HttpContext); var url = _session.GetUrlFromRequest(filterContext.HttpContext.Request); if (url.EndsWithAnyIgnoreCase(string.Format("/{0}", preferred), string.Format("/{0}/", preferred))) { return; } // Value is loose in the query string, i.e. '/?language=en' if (request.QueryString["language"] != null) { _session.Set(filterContext.HttpContext, request.QueryString["language"]); preferred = _session.GetLanguageFromSessionOrService(filterContext.HttpContext); } // Value is part of the explicit route, i.e. '/about/en' but not the preferred language var languages = request.UserLanguages ?? new[] { I18N.DefaultTwoLetterISOLanguageName }; foreach (var language in languages.Where(language => !string.IsNullOrWhiteSpace(language))) { var semiColonIndex = language.IndexOf(';'); var token = string.Format("/{0}", semiColonIndex > -1 ? language.Substring(0, semiColonIndex) : language); if (!url.EndsWithAnyIgnoreCase(token, string.Format("{0}/", token))) { continue; } // This is an explicit language request, override preferences _session.Set(filterContext.HttpContext, token.Substring(1)); preferred = _session.GetLanguageFromSessionOrService(filterContext.HttpContext); } RedirectWithLanguage(filterContext, values, preferred); }
public override VirtualPathData GetVirtualPath(RequestContext context, RouteValueDictionary values) { var result = _route.GetVirtualPath(context, values); if (result != null && result.VirtualPath != null) { var request = context.HttpContext.Request; if (!values.ContainsKey("language")) { if (request.QueryString["language"] != null) { result.VirtualPath = string.Format("{0}/{1}", result.VirtualPath, request.QueryString["language"]); } else { var language = _session.GetLanguageFromSessionOrService(context.HttpContext); var token = string.Format("/{0}", language); var url = _session.GetUrlFromRequest(context.HttpContext.Request); if (url.EndsWithAnyIgnoreCase(token, string.Format("{0}/", token))) { result.VirtualPath = result.VirtualPath.Equals("") ? language : string.Format("{0}/{1}", result.VirtualPath, language); } } } else { // Use pre-injected route value var baseUrl = context.HttpContext.Request.Url; if (baseUrl != null) { var relativeUrl = new Uri(baseUrl, values["language"].ToString()).PathAndQuery.Substring(1); result.VirtualPath = relativeUrl; } } } return(result); }