仅显示MVC网站的URL上的语言

时间:2015-07-15 23:50:37

标签: asp.net-mvc routing multilingual

我有一个用MVC 5开发的多语言项目,它也有路由。 URL显示如下:example.com/en-US,但现在我需要URL显示如下:example.com/en(没有' -US')或example.com/es

RouteConfig.cs文件:

using System.Web.Mvc;
using System.Web.Routing;

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

        routes.MapLocalizeRoute("Default",
            url: "{culture}/{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },

            constraints: new { culture = "[a-zA-Z]{2}-[a-zA-Z]{2}" });


        routes.MapRouteToLocalizeRedirect("RedirectToLocalize",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }
}
}

_Layout.cshtml文件:

<ul>                   
<li>@Html.ActionLink("Español", "ChangeLang", "Home", new { Lang = "es-ES", ReturnUrl = Url.Encode(Request.RawUrl) }, new { @class = "", @style = "" })</li>
<li>@Html.ActionLink("English", "ChangeLang", "Home", new { Lang = "en-US", ReturnUrl = Url.Encode(Request.RawUrl) }, new { @class = "", @style = "" })</li>
</ul>

LocalizedRouteHandler.cs文件:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace pascual_mvc
{
public class LocalizedRouteHandler : MvcRouteHandler
{
    protected override System.Web.IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
    {
        var urlLocale = requestContext.RouteData.Values["culture"] as string;
        var cultureName = urlLocale ?? "";

        var cookieLocale = requestContext.HttpContext.Request.Cookies["locale"];
        if (cookieLocale != null)
        {
            // if request contains locale cookie, we need to put higher priority than url locale
            // user might click the link from somewhere but he/she already set different locale
            if (!cookieLocale.Value.Equals(urlLocale, StringComparison.OrdinalIgnoreCase))
            {
                // if cookie locale and url cookie are different,
                // we should redirect with cookie locale
                var routeValues = requestContext.RouteData.Values;
                routeValues["culture"] = cookieLocale.Value;

                var queryString = requestContext.HttpContext.Request.QueryString;
                foreach (var key in queryString.AllKeys)
                {
                    if (!routeValues.ContainsKey(key))
                    {
                        routeValues.Add(key, queryString[key]);
                    }
                }

                return new RedirectHandler(new UrlHelper(requestContext).RouteUrl(routeValues));
            }
            else
            {
                cultureName = cookieLocale.Value;
            }
        }

        if (cultureName == "")
        {
            return GetDefaultLocaleRedirectHandler(requestContext);
        }

        try
        {
            var culture = CultureInfo.GetCultureInfo(cultureName);
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }
        catch (CultureNotFoundException)
        {
            // if CultureInfo.GetCultureInfo throws exception
            // we should redirect with default locale
            return GetDefaultLocaleRedirectHandler(requestContext);
        }

        if (cookieLocale == null)
        {
            requestContext.HttpContext.Response.AppendCookie(new HttpCookie("locale", cultureName));
        }
        return base.GetHttpHandler(requestContext);
    }

    private static IHttpHandler GetDefaultLocaleRedirectHandler(RequestContext requestContext)
    {
        var uiCulture = CultureInfo.CurrentUICulture;
        var routeValues = requestContext.RouteData.Values;
        routeValues["culture"] = uiCulture.Name;
        return new RedirectHandler(new UrlHelper(requestContext).RouteUrl(routeValues));
    }
}
}

我该如何更改这些代码?

我从此网站下载了该项目:http://www.jittuu.com/2014/3/17/AspNet-localization-routing/

1 个答案:

答案 0 :(得分:0)

我刚刚创建了一个映射表,可以从en映射到en-US。