Can my MVC2 app specify route constraints on Query String parameters?

我的未来我决定 提交于 2019-11-28 02:03:11

QueryString parameters can be used in constraints, although it's not supported by default. Here you can find an article describing how to implement this in ASP.NET MVC 2.

As it is in Dutch, here's the implementation. Add an 'IRouteConstraint' class:

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; 
    } 
}

Now you can use this in your routes:

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

You don't need a route for this. It is already handled by the default model binder. Query string parameters will be automatically bound to action arguments:

public ActionResult Foo(string id, string script, string vendorname)
{
    // the id parameter will be bound from the default route token
    // script and vendorname parameters will be bound from the request string
    ...    
}

UPDATE:

If you don't know the name of the query string parameters that will be passed you could loop through them:

foreach (string key in Request.QueryString.Keys)
{
    string value = Request.QueryString[key];
}

This post is old, but couldn't you write a route before your default route

this would only catch routes with "vendor" in the args

routes.MapRoute(
   null,
   "Document/Display/{id}?{args}",
   new { controller = "VendorController", action = "OtherAction" },
   new {args=@".*(vendor).*"}//believe this is correct regex to catch "vendor" anywhere in the args

);

And This would catch the rest

 routes.MapRoute(
       null,
       "Document/Display/{id}?{args}",
       new { controller = "DisplayController", action = "OtherAction" }
    );

Haven't tried this and I am a novice to MVC but I believe this should work?? From what I understand if the constraint doesn't match the route isn't used. So it would test the next route. Since your next route doesn't use any constraint on the args, it should, match the route.

I tried this out and it worked for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!