全局正则表达式匹配超时适用于控制台应用程序,但不适用于ASP.NET MVC应用程序

bal*_*pha 11 .net regex asp.net-mvc appdomain

我正在尝试使用.NET 4.5的新正则表达式匹配超时,特别是AppDomain.CurrentDomain.SetData具有"REGEX_DEFAULT_MATCH_TIMEOUT"属性的全局变体via (将您传递TimeSpan给正则表达式构造函数的变体工作正常).

当我使用这个main方法创建一个新的控制台应用程序:

static void Main(string[] args)
{
    AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT",
        TimeSpan.FromSeconds(3));

    var m = System.Text.RegularExpressions.Regex.Match(
        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "^(x+x+)+y$");
}
Run Code Online (Sandbox Code Playgroud)

它按预期工作:三秒后,它会抛出一个RegexMatchTimeoutException.

但是,如果我创建一个空的MVC 4应用程序,请添加一个HomeController和此操作方法:

public ActionResult Index()
{
    AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT",
        TimeSpan.FromSeconds(3));

    var m = System.Text.RegularExpressions.Regex.Match(
        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "^(x+x+)+y$");

    return View();
}
Run Code Online (Sandbox Code Playgroud)

并且访问http://localhost:XXXXX/没有异常被抛出并且匹配尝试继续.(如果你等待足够长的时间,它会最终完成,然后抱怨缺少的观点.这需要veeery长虽然).

调用SetDataGlobal.asaxApplication_Start(),而不是控制操作中不会使超时要么发生.

out*_*man 8

我猜这两个示例之间的区别在于您的控制台应用程序第二行是第一次访问RegEx对象,这是您初始化此类型的位置.在MVC中 - 我的猜测是在Index操作之前使用了RegEx类.

我尝试使用简单的控制台应用程序验证此行为,并获得与您在MVC中相同的结果:

var m = System.Text.RegularExpressions.Regex.Match(
    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "x");

AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", 
    TimeSpan.FromSeconds(3));

var m2 = System.Text.RegularExpressions.Regex.Match(
    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "^(x+x+)+y$");
Run Code Online (Sandbox Code Playgroud)

因此,您只需要确保在其他人使用之前初始化此属性.您可以使用web.config指定此配置:http:httpduntime部分中的http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.defaultregexmatchtimeout.aspx.