You need to enable JavaScript to run this app. 如何在ASP.NET Core的Route特性中设置正则匹配超时时间
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core的Route特性中设置正则匹配超时时间

ASP.NET Core路由正则约束设置超时的方案

方式1:全局配置所有路由正则约束的超时

这是最简便的方案,配置后对所有内置regex路由约束生效,无需修改现有路由特性代码:

// Program.cs 服务注册阶段配置
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRouting(options =>
{
    // 全局设置正则匹配超时为100毫秒,可根据业务调整
    options.RegexMatchTimeout = TimeSpan.FromMilliseconds(100);
});

你示例中的路由代码无需做任何修改,匹配正则时会自动使用该全局超时,超时后会直接判定路由不匹配,避免正则表达式拒绝服务攻击。

// 无需修改现有路由写法即可生效
[Route("[controller]/[action]/{test:regex(^(\\w+)$)}")]
public string Get(string test)
{
    // 业务逻辑
}

注意:你提供的示例正则存在括号不匹配的语法错误,修正后应为^(\\w+)$

方式2:为单个路由自定义专属超时

如果需要给特定路由的正则设置和全局不一样的超时,可以通过自定义参数化路由约束实现:

  1. 实现自定义正则约束类
using Microsoft.AspNetCore.Routing;
using System.Text.RegularExpressions;

public class CustomRegexConstraint : IParameterizedRouteConstraint
{
    private Regex? _regex;

    public void SetParameters(IReadOnlyList<string> parameters)
    {
        if (parameters.Count == 0)
            throw new ArgumentException("缺少必填的正则表达式参数");
        // 第一个参数为正则表达式
        var pattern = parameters[0];
        // 第二个参数为超时时间,单位毫秒,不传默认用100毫秒
        var timeout = parameters.Count > 1 && int.TryParse(parameters[1], out var ms) 
            ? TimeSpan.FromMilliseconds(ms) 
            : TimeSpan.FromMilliseconds(100);
        _regex = new Regex(pattern, RegexOptions.None, timeout);
    }

    public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (_regex == null)
            throw new InvalidOperationException("正则约束未完成初始化");
        if (!values.TryGetValue(routeKey, out var value) || value == null)
            return false;
        var input = Convert.ToString(value);
        return !string.IsNullOrEmpty(input) && _regex.IsMatch(input);
    }
}
  1. 注册自定义约束到路由系统
builder.Services.AddRouting(options =>
{
    // 注册自定义约束,别名customRegex
    options.ConstraintMap.Add("customRegex", typeof(CustomRegexConstraint));
    // 全局正则超时可同时配置,不冲突
    options.RegexMatchTimeout = TimeSpan.FromMilliseconds(100);
});
  1. 在路由特性中使用自定义约束
// 第二个参数指定当前正则的超时为200毫秒,优先级高于全局配置
[Route("[controller]/[action]/{test:customRegex(^(\\w+)$,200)}")]
public string Get(string test)
{
    // 业务逻辑
}

内容的提问来源于stack exchange,提问作者Mehdi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 09:15:06