Dot-Net

全域正則表達式匹配超時適用於控制台應用程序,但不適用於 ASP.NET MVC 應用程序

  • April 1, 2013

我正在嘗試使用 .NET 4.5 的新正則表達式匹配超時AppDomain.CurrentDomain.SetData,特別是通過屬性的全域變體"REGEX_DEFAULT_MATCH_TIMEOUT"(將 a 傳遞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$");
}

它按預期工作:三秒鐘後,它拋出一個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();
}

並且訪問http://localhost:XXXXX/沒有拋出異常並且匹配嘗試繼續。(如果您等待的時間足夠長,它最終會完成,然後抱怨缺少視圖。不過,這需要長時間。)

呼叫’s而不是在控制器操作SetData中呼叫也不會使超時發生。Global.asax``Application_Start()

我猜這兩個範例之間的區別在於,在您的控制台應用程序中,第二行是對 RegEx 對象的第一次訪問,這是您初始化此類型的地方。在 MVC 中 - 我猜想 RegEx 類是在您的 Index 操作之前使用的。

我嘗試使用簡單的控制台應用程序驗證此行為,並得到與 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$");

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

引用自:https://stackoverflow.com/questions/15742025