0

我正在尝试制作一个简单的多语言网站。覆盖 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/ 时,将不会重定向到站点的根目录。

路由的另一个问题是我不想让任何人输入控制器名称,我只想要操作,我的网站只有一个 Home 控制器,操作很少。

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

Mu Engine 我基于此解决方案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;
        }
    }
}
4

1 回答 1

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" });
于 2012-11-28T12:55:31.793 回答