首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IgnoreRoute的简写

IgnoreRoute的简写
EN

Stack Overflow用户
提问于 2012-06-26 06:53:14
回答 2查看 906关注 0票数 2

我注意到一个建议使用or-delimited matches for IgnoreRoute的SO答案,如下所示:

代码语言:javascript
复制
routes.IgnoreRoute("*.js|css|swf");

当我试着这样做的时候,它失败了。我必须将建议的一行代码转换为多行代码,如下所示:

代码语言:javascript
复制
routes.IgnoreRoute("Javascript/{*catchall}");
routes.IgnoreRoute("Content/{*catchall}");
routes.IgnoreRoute("Scripts/{*catchall}");

实际上,有没有一种更简洁的方式来表达对文件(例如css、javascript等)的豁免?另外,我想知道最初的链接是不是真的错了,或者我只是错过了什么。

是的,请假设我想要并需要routes.RouteExistingFiles = true

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-28 07:21:31

我想出了一个更简单的方法:

代码语言:javascript
复制
routes.RouteExistingFiles = true;
routes.IgnoreRoute("{*relpath}", new { relpath = @"(.*)?\.(css|js|htm|html)" });

也无需担心结尾的http查询字符串,因为System.Web.Routing.Route类已经在计算过程中去掉了这一部分。

有趣的是,Route.GetRouteData(...)中的代码将采用所提供的正则表达式约束,并添加“开始”和“结束”行要求,如下所示:

代码语言:javascript
复制
string str = myRegexStatementFromAbove;
string str2 = string.Concat("^(", str, ")$");

这就是为什么我写的正则表达式不能工作,如果它仅仅写成:

代码语言:javascript
复制
routes.IgnoreRoute("{*relpath}", new { relpath = @"\.(css|js|htm|html)" });
票数 2
EN

Stack Overflow用户

发布于 2012-06-26 12:08:41

我不确定您是否可以在一行中指定所有它们。另一种方法是,您可以创建自定义布线约束,并完全忽略那些文件夹/文件

更新:

根据来自@Brent的反馈,检查pathinfo比比较folder更好。

代码语言:javascript
复制
public class IgnoreConstraint : IRouteConstraint
{
    private readonly string[] _ignoreList;

    public IgnoreConstraint(params string[] ignoreList)
    {
        _ignoreList = ignoreList;
    }

    public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, 
    RouteValueDictionary values, RouteDirection routeDirection)
    {
        return _ignoreList.Contains(Path.GetExtension(values["pathinfo"].ToString()));
    }
}

Global.asax.cs

代码语言:javascript
复制
routes.IgnoreRoute("{*pathInfo}", new { c = 
           new IgnoreConstraint(".js", ".css") });

routes.RouteExistingFiles = true;

================================================================================

以前的代码

代码语言:javascript
复制
  public class IgnoreConstraint: IRouteConstraint
  {
    private readonly string[] _ignoreArray;

    public IgnoreConstraint(params string[] ignoreArray)
    {
      _ignoreArray = ignoreArray;
    }

    public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, 
      RouteValueDictionary values, RouteDirection routeDirection)
    {
      var folder = values["folder"].ToString().ToLower();

      return _ignoreArray.Contains(folder);
    }
  }

Global.asax.cs中的

代码语言:javascript
复制
routes.IgnoreRoute("{folder}/{*pathInfo}", new { c = 
          new IgnoreConstraint("content", "script") });

routes.RouteExistingFiles = true;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11198535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档