Exemplo n.º 1
0
        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));
        }
        /// <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);
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
        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(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;
            }));
        }
Exemplo n.º 6
0
        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());
        }