我的MVC2应用程序可以指定查询字符串参数的路由约束吗?

fli*_*ubt 4 routing components asp.net-mvc-2

我的MVC2应用程序使用一个组件,使后续的AJAX调用回到相同的操作,这会导致服务器上的各种不必要的数据访问和处理.组件供应商建议我将这些后续请求重新路由到不同的操作.后续请求的不同之处在于它们具有特定的查询字符串,我想知道是否可以在路由表中对查询字符串设置约束.

例如,初始请求带有一个URL,如http:// localhost/document/display/1.这可以通过默认路由处理.我想写一个自定义路由来处理像http:// localhost/document/display/1这样的URL ?vendorParam1 = blah1&script = blah.jshttp:// localhost/document/display/1?vendorParam2 = blah2&script = blah.js通过检测URL中的"供应商".

我试过以下,但它抛出一个System.ArgumentException: The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.:

routes.MapRoute(
   null,
   "Document/Display/{id}?{args}",
   new { controller = "OtherController", action = "OtherAction" },
   new RouteValueDictionary { { "args", "vendor" } });
Run Code Online (Sandbox Code Playgroud)

我可以编写一条考虑查询字符串的路由吗?如果没有,你还有其他想法吗?


更新:简单地说,我可以编写路由约束,使http:// localhost/document/display/1路由到DocumentController.Display操作但是http:// localhost/document/display/1?vendorParam1 = blah1&script = blah.js被路由在VendorController.Display行动?最后,我希望任何查询字符串包含"vendor"的URL都被路由到该VendorController.Display操作.

我知道第一个URL可以由默认路由处理,但第二个呢?是否可以这样做?经过大量的试验和错误,看起来答案是"不".

Jan*_*oom 8

QueryString参数可以在约束中使用,但默认情况下不支持. 在这里,您可以找到一篇描述如何在ASP.NET MVC 2中实现它的文章.

就像荷兰语一样,这是实施.添加'IRouteConstraint'类:

public class QueryStringConstraint : IRouteConstraint 
{ 
    private readonly Regex _regex; 

    public QueryStringConstraint(string regex) 
    { 
        _regex = new Regex(regex, RegexOptions.IgnoreCase); 
    } 

    public bool Match (HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
        // check whether the paramname is in the QS collection
        if(httpContext.Request.QueryString.AllKeys.Contains(parameterName)) 
        { 
            // validate on the given regex
            return _regex.Match(httpContext.Request.QueryString[parameterName]).Success; 
        } 
        // or return false
        return false; 
    } 
}
Run Code Online (Sandbox Code Playgroud)

现在您可以在路线中使用它:

routes.MapRoute("object-contact", 
    "{aanbod}", 
    /* ... */, 
    new { pagina = new QueryStringConstraint("some|constraint") });
Run Code Online (Sandbox Code Playgroud)