我注意到一个建议使用or-delimited matches for IgnoreRoute的SO答案,如下所示:
routes.IgnoreRoute("*.js|css|swf");当我试着这样做的时候,它失败了。我必须将建议的一行代码转换为多行代码,如下所示:
routes.IgnoreRoute("Javascript/{*catchall}");
routes.IgnoreRoute("Content/{*catchall}");
routes.IgnoreRoute("Scripts/{*catchall}");实际上,有没有一种更简洁的方式来表达对文件(例如css、javascript等)的豁免?另外,我想知道最初的链接是不是真的错了,或者我只是错过了什么。
是的,请假设我想要并需要routes.RouteExistingFiles = true
发布于 2012-06-28 07:21:31
我想出了一个更简单的方法:
routes.RouteExistingFiles = true;
routes.IgnoreRoute("{*relpath}", new { relpath = @"(.*)?\.(css|js|htm|html)" });也无需担心结尾的http查询字符串,因为System.Web.Routing.Route类已经在计算过程中去掉了这一部分。
有趣的是,Route.GetRouteData(...)中的代码将采用所提供的正则表达式约束,并添加“开始”和“结束”行要求,如下所示:
string str = myRegexStatementFromAbove;
string str2 = string.Concat("^(", str, ")$");这就是为什么我写的正则表达式不能工作,如果它仅仅写成:
routes.IgnoreRoute("{*relpath}", new { relpath = @"\.(css|js|htm|html)" });发布于 2012-06-26 12:08:41
我不确定您是否可以在一行中指定所有它们。另一种方法是,您可以创建自定义布线约束,并完全忽略那些文件夹/文件。
更新:
根据来自@Brent的反馈,检查pathinfo比比较folder更好。
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
routes.IgnoreRoute("{*pathInfo}", new { c =
new IgnoreConstraint(".js", ".css") });
routes.RouteExistingFiles = true;================================================================================
以前的代码
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中的
routes.IgnoreRoute("{folder}/{*pathInfo}", new { c =
new IgnoreConstraint("content", "script") });
routes.RouteExistingFiles = true;https://stackoverflow.com/questions/11198535
复制相似问题