Url.Action无法使用语言参数

时间:2014-11-13 13:05:55

标签: asp.net-mvc

我只有路线。配置如下:

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

我正在使用

创建链接
 <a href='@Url.Action("Index", "Results", new {     lang=System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName}')</a>

但链接根本没有被终止。我做错了什么?看起来很好。 我有索引操作和结果控制器。当我有默认路由MVC附带{controller} / {action}

时,这没关系

这是LanguageConstraint:

      public class LanguageConstraint : IRouteConstraint
{
    public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (routeDirection == RouteDirection.IncomingRequest)
        {
            string language = values["lang"].ToString();  //(en|hr|de|it|fr|sk|nl|hu|sv|pl|cs|ru|sl
            if (language == "en" || language == "hr" || language == "de" || language == "it" || language == "fr" || language == "sk" || language == "nl" || 
                language == "hu" || language == "sv" || language == "pl" || language == "cs" || language == "ru" || language == "sl" )
                return true;
            else
                return false;
        }
        return false;
    }
}

1 个答案:

答案 0 :(得分:1)

你应该改变这样的方法我认为

public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
    if (routeDirection == RouteDirection.IncomingRequest)
    {
        string language = values["lang"].ToString();  //(en|hr|de|it|fr|sk|nl|hu|sv|pl|cs|ru|sl
        if (language == "en" || language == "hr" || language == "de" || language == "it" || language == "fr" || language == "sk" || language == "nl" || 
            language == "hu" || language == "sv" || language == "pl" || language == "cs" || language == "ru" || language == "sl" )
            return true;
        else
            return false;
    }
    return true;
}

创建链接时routeDirection的问题是RouteDirection.UrlGeneration