使用多个路由的本地化ViewEngines

时间:2012-11-27 15:28:57

标签: razor localization asp.net-mvc-4 locale viewengine

我正在尝试制作一个简单的多语言网站。重写FindView以根据语言获取文件很容易,我的问题出现在路由部分。

我想做的是:(有一个网站有2种语言 - pt-br和en-us,让缩写为onlu pt和en - 默认为PT)

用户类型www.mysite.com - >会在用户标头请求中找到这些语言,如果用户没有这些语言,他将被重定向到默认的PT,因此最终结果将是葡萄牙语www.mysite.com。如果他有en,他将被重定向到www.mysite.com/en/,结果将是英文视图。

如果用户输入www.mysite.com/pt/ - >我会检查他是否想要默认值,并将用葡萄牙语重定向到www.mysite.com。

我做了一个自定义引擎,以根据语言获得正确的视图。但由于路由问题,它不能100%工作。

在我的情况下,我试图用

路由
routes.MapRoute(
                "Localization", // Route name
                "{lang}/{controller}/{action}", // URL with parameters
                new { lang = "pt", controller = "Home", action = "Index" } //defaults
);

但是有了这个,当有人输入/ pt /不会重定向到网站的根目录时。

该路线的另一个问题是我不想让任何人输入控制器名称,我只想要动作,我的网站只有一个家庭控制器,几乎没有动作。

另一个问题是,我需要一个不同的动作名称,例如英语的CONTACT和葡萄牙语的CONTATO,它们应该出现在地址栏上,如www.mysite.com/Contato或www.mysite.com/en/Contact

我根据http://www.counity.at/blog/2012/asp-net-mvc3-localization-using-culture-dependent-views/

确定了Guido Breitenhuber此解决方案

这是带有一些调整的代码(它还没有100%工作)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Globalization;

namespace Ala.MultiLanguage
{
    public class LocalizedViewLocation : RazorViewEngine
    {
        private static readonly string[] _emptyLocations = new string[0];

        public string[] LocalizedViewLocationFormats { get; set; }

        public string[] LocalizedMasterLocationFormats { get; set; }

        protected string[] LocalizedPartialViewLocationFormats { get; set; }

        public LocalizedViewLocation()
        {
            // Define the localized view locations
            //  0: Language
            //  1: View name
            //  2: Controller name

            LocalizedViewLocationFormats = new[] {
            "~/Views/{0}/{2}/{1}.cshtml",
            "~/Views/Shared/{0}/{1}.cshtml"};

            MasterLocationFormats = new[] {
            "~/Views/{0}/{2}/{1}.cshtml",
            "~/Views/Shared/{0}/{1}.cshtml"};

            LocalizedPartialViewLocationFormats = new[] {
            "~/Views/{0}/{2}/{1}.cshtml",
            "~/Views/Shared/{0}/{1}.cshtml"};
        }


        public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext");

            if (String.IsNullOrEmpty(partialViewName))
                throw new ArgumentException("Parameter partialViewName is null or empty.", "partialViewName");

            string[] searched;

            var controllerName = controllerContext.RouteData.GetRequiredString("controller");

            var partialPath = GetPath(controllerContext, LocalizedPartialViewLocationFormats, partialViewName, controllerName, out searched);


            if (String.IsNullOrEmpty(partialPath))
            {
                var baseRes = base.FindPartialView(controllerContext, partialViewName, useCache);

                if (baseRes.View != null)
                    return baseRes;

                return new ViewEngineResult(searched.Union(baseRes.SearchedLocations));
            }

            return new ViewEngineResult(CreatePartialView(controllerContext, partialPath), this);
        }

        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext");

            if (String.IsNullOrEmpty(viewName))
                throw new ArgumentException("Parameter viewName is null or empty.", "viewName");

            string[] viewLocationsSearched;

            string[] masterLocationsSearched;

            var controllerName = controllerContext.RouteData.GetRequiredString("controller");

            var viewPath = GetPath(controllerContext, LocalizedViewLocationFormats, viewName, controllerName, out viewLocationsSearched);

            var masterPath = GetPath(controllerContext, LocalizedMasterLocationFormats, masterName, controllerName, out masterLocationsSearched);


            if (String.IsNullOrEmpty(viewPath) || (String.IsNullOrEmpty(masterPath) && !String.IsNullOrEmpty(masterName)))
            {
                var baseRes = base.FindView(controllerContext, viewName, masterName, useCache);

                if (baseRes.View != null)
                    return baseRes;

                return new ViewEngineResult(viewLocationsSearched.Union(masterLocationsSearched).Union(baseRes.SearchedLocations));
            }

            return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);
        }


        private string GetPath(ControllerContext controllerContext, string[] locations, string name, string controllerName, out string[] searchedLocations)
        {
            searchedLocations = _emptyLocations;

            if (String.IsNullOrEmpty(name))
                return String.Empty;

            if (IsSpecificPath(name))
                return String.Empty;

            return GetPathFromGeneralName(controllerContext, locations, name, controllerName, ref searchedLocations);
        }


        private static bool IsSpecificPath(string name)
        {
            char c = name[0];
            return (c == '~' || c == '/');
        }

        private string GetPathFromGeneralName(ControllerContext controllerContext, string[] locations, string name, string controllerName, ref string[] searchedLocations)
        {
            var result = String.Empty;

            searchedLocations = new string[locations.Length];

            for (int i = 0; i < locations.Length; i++)
            {
                var location = locations[i];

                var virtualPath = string.Format(CultureInfo.InvariantCulture, location, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, name, controllerName);

                if (FileExists(controllerContext, virtualPath))
                {
                    searchedLocations = _emptyLocations;

                    result = virtualPath;

                    break;
                }

                searchedLocations[i] = virtualPath;
            }

            return result;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

好吧,经过一段时间尝试以最佳方式完成后,我发现一种解决方案更容易,更快速地实施。

只是在global.asax中逐一映射我想要的路由。如果您只有很少的页面和语言,这将有效,并且可以快速实施。

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute("Default-BR", "", new { controller = "Home", action = "Index" });
    routes.MapRoute("Default-EN", "en", new { controller = "Home", action = "IndexEN" });

    routes.MapRoute("HotelBR", "Hotel", new { controller = "Home", action = "Index" });
    routes.MapRoute("HotelEN", "en/Hotel", new { controller = "Home", action = "IndexEN" });

    routes.MapRoute("Apartamento", "Apartamento", new { controller = "Home", action = "Apartamentos" });
    routes.MapRoute("Apartamentos", "Apartamentos", new { controller = "Home", action = "Apartamentos" });
    routes.MapRoute("Apartments", "en/Apartments", new { controller = "Home", action = "ApartamentosEN" });

    routes.MapRoute("Localizacao", "Localizacao", new { controller = "Home", action = "Localizacao" });
    routes.MapRoute("Location", "en/Location", new { controller = "Home", action = "LocalizacaoEN" });

    routes.MapRoute("Tarifa", "Tarifa", new { controller = "Home", action = "Tarifas" });
    routes.MapRoute("Tarifas", "Tarifas", new { controller = "Home", action = "Tarifas" });
    routes.MapRoute("Rates", "en/Rates", new { controller = "Home", action = "TarifasEN" });

    routes.MapRoute("Reserva", "Reserva", new { controller = "Home", action = "Reservas" });
    routes.MapRoute("Reservas", "Reservas", new { controller = "Home", action = "Reservas" });
    routes.MapRoute("Booking", "en/Booking", new { controller = "Home", action = "ReservasEN" });

    routes.MapRoute("Contato", "Contato", new { controller = "Home", action = "Contato" });
    routes.MapRoute("Contact", "en/Contact", new { controller = "Home", action = "ContatoEN" });