加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-2 – 我的MVC2应用程序可以在查询字符串参数上指定

发布时间:2020-12-16 07:22:16 所属栏目:asp.Net 来源:网络整理
导读:我的MVC2应用程序使用一个组件,使后续的 AJAX调用回到相同的操作,这会导致服务器上的各种不必要的数据访问和处理.组件供应商建议我将这些后续请求重新路由到不同的操作.后续请求的不同之处在于它们具有特定的查询字符串,我想知道是否可以在路由表中对查询字
我的MVC2应用程序使用一个组件,使后续的 AJAX调用回到相同的操作,这会导致服务器上的各种不必要的数据访问和处理.组件供应商建议我将这些后续请求重新路由到不同的操作.后续请求的不同之处在于它们具有特定的查询字符串,我想知道是否可以在路由表中对查询字符串设置约束.

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

我尝试了以下方法,但它抛出了一个System.ArgumentException:路由URL不能以’/’或’?’字符开头,它不能包含’?’字符.:

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

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

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

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

解决方法

QueryString参数可以在约束中使用,但默认情况下不支持. Here您可以在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; 
    } 
}

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读