当语言环境发生变化时,Html.Routelink会生成不同的URL

时间:2015-12-11 08:29:13

标签: asp.net-mvc-4 localization asp.net-mvc-routing

我的网站可以用荷兰语,英语和德语阅读。用户可以通过单击页面顶部的标志来选择他们喜欢的语言。链接的呈现方式如下:

<ul class="nav navbar-nav navbar-right flag">
                @if (Request.IsAuthenticated) {
                    if (model.AvailableLanguages.Contains("NL")) {
                        <li class="flagNL" title="Nederlands">@Html.RouteLink(" ", new { locale = "nl-NL" })</li>
                    }

                    if (model.AvailableLanguages.Contains("DE")) {
                        <li class="flagDE" title="Deutsch">@Html.RouteLink(" ", new { locale = "de-DE" })</li>
                    }

                    if (model.AvailableLanguages.Contains("EN")) {
                        <li class="flagGB" title="English">@Html.RouteLink(" ", new { locale = "en-GB" })</li>
                    }
                }
                else {
                    var qs = (!string.IsNullOrEmpty(Request.QueryString.ToString()) && Request.QueryString["ReturnUrl"] != null) ? Request.QueryString["ReturnUrl"] : string.Empty;

                    if (model.AvailableLanguages.Contains("NL")) {
                        <li class="flagNL" title="Nederlands">@Html.RouteLink(" ", new { locale = "nl-NL", ReturnUrl = Server.UrlDecode(qs) })</li>
                    }

                    if (model.AvailableLanguages.Contains("DE")) {
                        <li class="flagDE" title="Deutsch">@Html.RouteLink(" ", new { locale = "de-DE", ReturnUrl = Server.UrlDecode(qs) })</li>
                    }

                    if (model.AvailableLanguages.Contains("EN")) {
                        <li class="flagGB" title="English">@Html.RouteLink(" ", new { locale = "en-GB", ReturnUrl = Server.UrlDecode(qs) })</li>
                    }
                }
            </ul>

我无法理解为什么会导致呈现3个不同的基本URL。当我用德语浏览网站时,链接是:

荷兰语:webserver.local/?ReturnUrl=%2F
对于德语:webserver.local/de-DE/Account/Login?ReturnUrl=%2F
对于英语:webserver.local/en-GB?ReturnUrl=%2F

最大的问题是,当我点击荷兰语时,网站会抛出错误,HTTP 401 - 未经授权。一个较小的问题是当语言切换时,深层链接会丢失。任何建议将不胜感激。

编辑:和请求的RouteConfig:

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

            routes.IgnoreRoute("favicon.ico");

            State state = new State();

            routes.MapRoute(
                name: "Localization",
                url: "{locale}/{controller}/{action}/{id}",
                defaults: new { locale = "nl-NL", controller = "Home", action = "Index", id = UrlParameter.Optional },
                constraints: new { locale = "[a-zA-Z]{2}-[a-zA-Z]{2}" }
            );

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

0 个答案:

没有答案