如何全球改变路线?

时间:2012-06-27 10:19:26

标签: asp.net .net asp.net-mvc asp.net-mvc-3 routes

我希望在两种语言(PL和EN)之间切换MVC 3中的视图。我在Views-EN和PL中创建了两个文件夹。因此,在任何网站点击相应的语言链接后,我希望我的路线更改为:

routes.MapRoute(
                "pl", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "PL", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

为:

routes.MapRoute(
                "en", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "EN", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

当我点击相应的链接(语言切换器)时,它会更改对所有线程持久的CultureInfo。 _Layout View with switcher:

<ul>
    <li>@Html.ActionLink("En", "ChangeCulture", null, new { lang = "en"}, null)</li>
    <li>@Html.ActionLink("Pl", "ChangeCulture", null, new { lang = "pl"}, null)</li>
</ul>

和controller(它还设置了静态变量lang,可以在每个控制器的方法中看到并在请求之间保持不变):

public ActionResult ChangeCulture(string lang)
    {

        PLController.lang = lang;
        CultureSettings setCulture = new CultureSettings();
        setCulture.InitializeCulture(lang);
        cookie.Value = CultureInfo.CurrentCulture.Name;
        this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
        return View("Index");
    }

InitializeCulture方法从Page类重写,如下所示:

public class CultureSettings : Page{

    public void InitializeCulture(string culture)
    {
            String selectedLanguage;
            if(culture == null)
            {
                selectedLanguage = "pl";
            }
            else
            {
                selectedLanguage = culture;
            }

            UICulture = selectedLanguage;
            Culture = selectedLanguage;

            Thread.CurrentThread.CurrentCulture =
                CultureInfo.CreateSpecificCulture(selectedLanguage);
            Thread.CurrentThread.CurrentUICulture = new
                CultureInfo(selectedLanguage);

        base.InitializeCulture();
    }
}

正确设置CultureInfo。现在我想(根据当前的CultureInfo)切换每个导航链接的路线并将路线模式从mysite.com/PL/ {controller} / {action}更改为mysite.com/EN/{controller}/{action}.

有没有人对此问题有任何想法或更好的方法?但条件是地址必须看起来像这样的mysite.com/EN或mysite.com/PL - 没有区别(即en.mysite.com)

2 个答案:

答案 0 :(得分:6)

您必须决定的第一件事是存储当前用户语言的位置。有不同的可能性:

  • 每个网址的一部分
  • 饼干
  • 会话

恕我直言,出于搜索引擎优化的目的,最好将它作为网址的一部分。

所以我建议编写一个自定义路由,它将解析网址中的语言并设置当前的线程文化:

public class LocalizedRoute : Route
{
    public LocalizedRoute()
        : base(
            "{lang}/{controller}/{action}/{id}",
            new RouteValueDictionary(new
            {
                lang = "en-US",
                controller = "home",
                action = "index",
                id = UrlParameter.Optional
            }),
            new RouteValueDictionary(new
            {
                lang = @"[a-z]{2}-[a-z]{2}"
            }),
            new MvcRouteHandler()
        )
    {
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        if (rd == null)
        {
            return null;
        }

        var lang = rd.Values["lang"] as string;
        if (string.IsNullOrEmpty(lang))
        {
            // pick a default culture
            lang = "en-US";
        }

        var culture = new CultureInfo(lang);

        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;

        return rd;
    }
}

我们现在可以在Global.asax注册此自定义路线:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.Add("Default", new LocalizedRoute());
}

好的,现在让我们有一个模型:

public class MyViewModel
{
    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime Date { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Date = DateTime.Now
        });
    }

    public ActionResult Test()
    {
        return Content(DateTime.Now.ToLongDateString());
    }
}

观点:

@model MyViewModel

@Html.DisplayFor(x => x.Date)

<ul>
    <li>@Html.ActionLink("switch to fr-FR", "index", new { lang = "fr-FR" })</li>
    <li>@Html.ActionLink("switch to de-DE", "index", new { lang = "de-DE" })</li>
    <li>@Html.ActionLink("switch to en-US", "index", new { lang = "en-US" })</li>
</ul>

@Html.ActionLink("Test culture", "test")

现在,当您点击链接时,我们正在更改语言,此语言现在是路线的一部分。请注意,一旦您选择了该语言,该语言将保留在test链接的路由中。

Scott Hanselman还在ASP.NET中写了一篇关于本地化和全球化的nice blog post,值得一试。

答案 1 :(得分:0)

此解决方案无法解决此问题:

english: /en/home

french: /fr/accueil

english: /en/contactus

french: /fr/contacteznous

它只会做

/en/home

/fr/home

您还应该在字典中本地化路线并进行查找。