public async Task <IActionResult> SetLanguage(int langid, string returnUrl = "") { var language = await _db.Languages.FindByIdAsync(langid, false); if (language != null && language.Published) { Services.WorkContext.WorkingLanguage = language; } var helper = new LocalizedUrlHelper(Request.PathBase, returnUrl ?? string.Empty); if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled) { // Don't prepend culture code if it is master language and master is prefixless by configuration. string defaultSeoCode = await _languageService.Value.GetMasterLanguageSeoCodeAsync(); if (language.UniqueSeoCode != defaultSeoCode && _localizationSettings.DefaultLanguageRedirectBehaviour == 0) { helper.PrependCultureCode(Services.WorkContext.WorkingLanguage.UniqueSeoCode, true); } } returnUrl = helper.FullPath; return(RedirectToReferrer(returnUrl)); }
public ActionResult SetLanguage(int langid, string returnUrl = "") { var language = _languageService.GetLanguageById(langid); if (language != null && language.Published) { _services.WorkContext.WorkingLanguage = language; } // url referrer if (String.IsNullOrEmpty(returnUrl)) { returnUrl = _services.WebHelper.GetUrlReferrer(); } // home page if (String.IsNullOrEmpty(returnUrl)) { returnUrl = Url.RouteUrl("HomePage"); } if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled) { var helper = new LocalizedUrlHelper(HttpContext.Request.ApplicationPath, returnUrl, true); helper.PrependSeoCode(_services.WorkContext.WorkingLanguage.UniqueSeoCode, true); returnUrl = helper.GetAbsolutePath(); } return(Redirect(returnUrl)); }
private LocalizedUrlHelper CreateUrlHelperForLanguageSelector(LanguageModel model, int currentLanguageId) { if (currentLanguageId != model.Id) { var routeValues = this.Request.RequestContext.RouteData.Values; var controller = routeValues["controller"].ToString(); if (!routeValues.TryGetValue(controller + "id", out var val)) { controller = routeValues["action"].ToString(); routeValues.TryGetValue(controller + "id", out val); } int entityId = 0; if (val != null) { entityId = val.Convert <int>(); } if (entityId > 0) { var activeSlug = _urlRecordService.Value.GetActiveSlug(entityId, controller, model.Id); if (activeSlug.HasValue()) { var helper = new LocalizedUrlHelper(Request.ApplicationPath, activeSlug, false); return(helper); } } } return(new LocalizedUrlHelper(HttpContext.Request, true)); }
/// <summary> /// Creates an absolute product URL. /// </summary> /// <param name="productId">Product identifier</param> /// <param name="productSeName">Product SEO name</param> /// <param name="attributesXml">XML formatted attributes</param> /// <param name="store">Store entity</param> /// <param name="language">Language entity</param> /// <returns>Absolute product URL</returns> public virtual string GetAbsoluteProductUrl( int productId, string productSeName, string attributesXml, Store store = null, Language language = null) { if (_httpRequest == null || productSeName.IsEmpty()) { return(null); } var url = Url; if (url.IsEmpty()) { // No given URL. Create SEO friendly URL. var urlHelper = new LocalizedUrlHelper(_httpRequest.ApplicationPath, productSeName, false); store = store ?? _services.StoreContext.CurrentStore; language = language ?? _services.WorkContext.WorkingLanguage; if (_localizationSettings.Value.SeoFriendlyUrlsForLanguagesEnabled) { var defaultSeoCode = _languageService.Value.GetDefaultLanguageSeoCode(store.Id); if (language.UniqueSeoCode == defaultSeoCode && _localizationSettings.Value.DefaultLanguageRedirectBehaviour > 0) { urlHelper.StripSeoCode(); } else { urlHelper.PrependSeoCode(language.UniqueSeoCode, true); } } var storeUrl = store.Url.TrimEnd('/'); // Prevent duplicate occurrence of application path. if (urlHelper.ApplicationPath.HasValue() && storeUrl.EndsWith(urlHelper.ApplicationPath, StringComparison.OrdinalIgnoreCase)) { storeUrl = storeUrl.Substring(0, storeUrl.Length - urlHelper.ApplicationPath.Length).TrimEnd('/'); } url = storeUrl + urlHelper.GetAbsolutePath(); } if (attributesXml.HasValue()) { var query = new ProductVariantQuery(); DeserializeQuery(query, productId, attributesXml); url = url + ToQueryString(query); } return(url); }
protected LanguageSelectorModel PrepareLanguageSelectorModel() { var availableLanguages = _cacheManager.Get(string.Format(ModelCacheEventConsumer.AVAILABLE_LANGUAGES_MODEL_KEY, _storeContext.CurrentStore.Id), () => { var result = _languageService .GetAllLanguages(storeId: _storeContext.CurrentStore.Id) .Select(x => new LanguageModel() { Id = x.Id, Name = x.Name, // codehint: sm-add NativeName = GetLanguageNativeName(x.LanguageCulture) ?? x.Name, ISOCode = x.LanguageCulture, SeoCode = x.UniqueSeoCode, FlagImageFileName = x.FlagImageFileName }) .ToList(); return(result); }); var workingLanguage = _workContext.WorkingLanguage; var model = new LanguageSelectorModel() { CurrentLanguageId = workingLanguage.Id, AvailableLanguages = availableLanguages, UseImages = _localizationSettings.UseImagesForLanguageSelection }; string defaultSeoCode = _workContext.GetDefaultLanguageSeoCode(); foreach (var lang in model.AvailableLanguages) { var helper = new LocalizedUrlHelper(HttpContext.Request, true); if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled) { if (lang.SeoCode == defaultSeoCode && (int)(_localizationSettings.DefaultLanguageRedirectBehaviour) > 0) { helper.StripSeoCode(); } else { helper.PrependSeoCode(lang.SeoCode, true); } } model.ReturnUrls[lang.SeoCode] = HttpUtility.UrlEncode(helper.GetAbsolutePath()); } return(model); }
public UrlPolicy(HttpRequest request) { Guard.NotNull(request, nameof(request)); var helper = new LocalizedUrlHelper(request); var path = helper.StripCultureCode(out var cultureCode); Scheme = new UrlSegment(request.Scheme); Host = new UrlSegment(request.Host.Value); PathBase = new UrlSegment(request.PathBase.Value?.Trim('/')); Culture = new UrlSegment(cultureCode); Path = new UrlSegment(path); QueryString = new UrlSegment(request.QueryString.Value); Method = request.Method; }
public ActionResult SetLanguage(int langid, string returnUrl = "") { var language = _languageService.Value.GetLanguageById(langid); if (language != null && language.Published) { _services.WorkContext.WorkingLanguage = language; } if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled) { var helper = new LocalizedUrlHelper(HttpContext.Request.ApplicationPath, returnUrl, false); helper.PrependSeoCode(_services.WorkContext.WorkingLanguage.UniqueSeoCode, true); returnUrl = helper.GetAbsolutePath(); } return(RedirectToReferrer(returnUrl)); }
private static PathInfo GetCurrentPathInfo(ActionContext actionContext) { var cacheKey = "CurrentPathInfoForSitemapMatching"; return(actionContext.HttpContext.GetItem(cacheKey, () => { //var requestContext = controllerContext.RequestContext; var request = actionContext.HttpContext.Request; var urlHelper = new LocalizedUrlHelper(request); urlHelper.StripCultureCode(out var cultureCode); var info = new PathInfo { RequestPath = urlHelper.FullPath }; // TODO: implement when routes are available. // Path generated by Routing var routeValues = actionContext.RouteData.Values; //if (requestContext.RouteData.Route is GenericPathRoute) //{ // // We pushed matching UrlRecord instance to DataTokens in GenericPathRoute class // var urlRecord = requestContext.RouteData.DataTokens["UrlRecord"] as UrlRecord; // if (urlRecord != null) // { // var routeName = urlRecord.EntityName; // // Also SeName has been pushed to current RouteValues in GenericPathRoute class // if (routeValues.ContainsKey("SeName")) // { // info.RoutePath = new UrlHelper(requestContext).RouteUrl(routeName, new { SeName = routeValues["SeName"] })?.ToLower(); // } // } //} //else //{ // info.RoutePath = new UrlHelper(requestContext).RouteUrl(routeValues)?.ToLower(); //} return info; })); }
public async Task <IActionResult> SetLanguage(int langid, string returnUrl = "") { var language = await _db.Languages.FindByIdAsync(langid); if (language != null && language.Published) { Services.WorkContext.WorkingLanguage = language; } var helper = new LocalizedUrlHelper(Request.PathBase, returnUrl ?? string.Empty); if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled) { // TODO: (mh) (core) Don't prepend code if it is master language and master is prefixless by configuration. helper.PrependCultureCode(Services.WorkContext.WorkingLanguage.UniqueSeoCode, true); } returnUrl = helper.FullPath; return(RedirectToReferrer(returnUrl)); }
private static PathInfo GetCurrentPathInfo(ControllerContext controllerContext) { var cacheKey = "CurrentPathInfoForSitemapMatching"; return(controllerContext.HttpContext.GetItem <PathInfo>(cacheKey, () => { var requestContext = controllerContext.RequestContext; var request = controllerContext.HttpContext.Request; var urlHelper = new LocalizedUrlHelper(request, true); urlHelper.StripSeoCode(); var info = new PathInfo { RequestPath = urlHelper.GetAbsolutePath().ToLower() }; // Path generated by Routing var routeValues = requestContext.RouteData.Values; if (requestContext.RouteData.Route is GenericPathRoute) { // We pushed matching UrlRecord instance to DataTokens in GenericPathRoute class var urlRecord = requestContext.RouteData.DataTokens["UrlRecord"] as UrlRecord; if (urlRecord != null) { var routeName = urlRecord.EntityName; // Also SeName has been pushed to current RouteValues in GenericPathRoute class if (routeValues.ContainsKey("SeName")) { info.RoutePath = new UrlHelper(requestContext).RouteUrl(routeName, new { SeName = routeValues["SeName"] })?.ToLower(); } } } else { info.RoutePath = new UrlHelper(requestContext).RouteUrl(routeValues)?.ToLower(); } return info; })); }
private async Task <LocalizedUrlHelper> CreateUrlHelperForLanguageSelectorAsync(LanguageModel model, int currentLanguageId) { // TODO: (mh) (core) Debug & Test once product actions are implemented. if (currentLanguageId != model.Id) { var routeValues = Request.RouteValues; var controllerName = routeValues.GetControllerName(); if (!routeValues.TryGetValue(controllerName + "id", out var val)) { controllerName = routeValues.GetActionName(); routeValues.TryGetValue(controllerName + "id", out val); } int entityId = 0; if (val != null) { entityId = val.Convert <int>(); } if (entityId > 0) { var activeSlug = await _urlService.GetActiveSlugAsync(entityId, controllerName, model.Id); if (activeSlug.IsEmpty()) { // Fallback to default value. activeSlug = await _urlService.GetActiveSlugAsync(entityId, controllerName, 0); } if (activeSlug.HasValue()) { var helper = new LocalizedUrlHelper(Request.PathBase, activeSlug); return(helper); } } } return(new LocalizedUrlHelper(Request)); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext == null || filterContext.HttpContext == null) { return; } HttpRequestBase request = filterContext.HttpContext.Request; if (request == null) { return; } //don't apply filter to child methods if (filterContext.IsChildAction) { return; } //only GET requests if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { return; } // ensure that this route is registered and localizable (LocalizedRoute in RouteProvider.cs) if (filterContext.RouteData == null || filterContext.RouteData.Route == null || !(filterContext.RouteData.Route is LocalizedRoute)) { return; } if (!DataSettings.DatabaseIsInstalled()) { return; } var localizationSettings = LocalizationSettings.Value; if (!localizationSettings.SeoFriendlyUrlsForLanguagesEnabled) { return; } // process current URL var workContext = WorkContext.Value; var languageService = LanguageService.Value; var workingLanguage = workContext.WorkingLanguage; var helper = new LocalizedUrlHelper(filterContext.HttpContext.Request, true); string defaultSeoCode = languageService.GetDefaultLanguageSeoCode(); string seoCode; if (helper.IsLocalizedUrl(out seoCode)) { if (!languageService.IsPublishedLanguage(seoCode)) { var descriptor = filterContext.ActionDescriptor; // language is not defined in system or not assigned to store if (localizationSettings.InvalidLanguageRedirectBehaviour == InvalidLanguageRedirectBehaviour.ReturnHttp404) { filterContext.Result = new ViewResult { ViewName = "NotFound", MasterName = (string)null, ViewData = new ViewDataDictionary <HandleErrorInfo>(new HandleErrorInfo(new HttpException(404, "The resource does not exist."), descriptor.ActionName, descriptor.ControllerDescriptor.ControllerName)), TempData = filterContext.Controller.TempData }; filterContext.RouteData.Values["StripInvalidSeoCode"] = true; filterContext.RequestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound; filterContext.RequestContext.HttpContext.Response.TrySkipIisCustomErrors = true; } else if (localizationSettings.InvalidLanguageRedirectBehaviour == InvalidLanguageRedirectBehaviour.FallbackToWorkingLanguage) { helper.StripSeoCode(); filterContext.Result = new RedirectResult(helper.GetAbsolutePath(), true); } } else { // redirect default language (if desired) if (seoCode == defaultSeoCode && localizationSettings.DefaultLanguageRedirectBehaviour == DefaultLanguageRedirectBehaviour.StripSeoCode) { helper.StripSeoCode(); filterContext.Result = new RedirectResult(helper.GetAbsolutePath(), true); } } // already localized URL, skip the rest return; } // keep default language prefixless (if desired) if (workingLanguage.UniqueSeoCode == defaultSeoCode && (int)(localizationSettings.DefaultLanguageRedirectBehaviour) > 0) { return; } // add language code to URL helper.PrependSeoCode(workingLanguage.UniqueSeoCode); filterContext.Result = new RedirectResult(helper.GetAbsolutePath()); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext == null || filterContext.HttpContext == null) { return; } HttpRequestBase request = filterContext.HttpContext.Request; if (request == null) { return; } //don't apply filter to child methods if (filterContext.IsChildAction) { return; } //only GET requests if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { return; } // ensure that this route is registered and localizable (LocalizedRoute in RouteProvider.cs) if (filterContext.RouteData == null || filterContext.RouteData.Route == null || !(filterContext.RouteData.Route is LocalizedRoute)) { return; } if (!DataSettings.DatabaseIsInstalled()) { return; } var localizationSettings = EngineContext.Current.Resolve <LocalizationSettings>(); if (!localizationSettings.SeoFriendlyUrlsForLanguagesEnabled) { return; } // process current URL var workContext = EngineContext.Current.Resolve <IWorkContext>(); var workingLanguage = workContext.WorkingLanguage; var helper = new LocalizedUrlHelper(filterContext.HttpContext.Request, true); string defaultSeoCode = workContext.GetDefaultLanguageSeoCode(); string seoCode; if (helper.IsLocalizedUrl(out seoCode)) { if (!workContext.IsPublishedLanguage(seoCode)) { // language is not defined in system or not assigned to store if (localizationSettings.InvalidLanguageRedirectBehaviour == InvalidLanguageRedirectBehaviour.ReturnHttp404) { filterContext.Result = new RedirectResult("~/404"); } else if (localizationSettings.InvalidLanguageRedirectBehaviour == InvalidLanguageRedirectBehaviour.FallbackToWorkingLanguage) { helper.StripSeoCode(); filterContext.Result = new RedirectResult(helper.GetAbsolutePath(), true); } } else { // redirect default language (if desired) if (seoCode == defaultSeoCode && localizationSettings.DefaultLanguageRedirectBehaviour == DefaultLanguageRedirectBehaviour.StripSeoCode) { helper.StripSeoCode(); filterContext.Result = new RedirectResult(helper.GetAbsolutePath(), true); } } // already localized URL, skip the rest return; } // keep default language prefixless (if desired) if (workingLanguage.UniqueSeoCode == defaultSeoCode && (int)(localizationSettings.DefaultLanguageRedirectBehaviour) > 0) { return; } // add language code to URL helper.PrependSeoCode(workingLanguage.UniqueSeoCode); filterContext.Result = new RedirectResult(helper.GetAbsolutePath()); }