原理
语法
示例
新建文件夹CustomRouteConstraints,在此文件夹下新建类MonthsCustomRouteConstraint.cs
public class MonthsCustomRouteConstraint : IRouteConstraint
{
//"sales-report/{year:int:min(1900)}/{month:regex(^(apr|jul|oct|jan)$)}"
//httpContext相当于中间件中的context
//route被应用此路由约束的路由
//routeKey相当于上面例子中的year/name中某个路由参数
//values包含了路由中所有参数
//routeDirection当有URL生成的时候是否需要检查收到的路由
public bool Match(HttpContext? httpContext, IRouter? route, string routeKey,
RouteValueDictionary values, RouteDirection routeDirection)
{
//check weather the value exists
if (!values.ContainsKey(routeKey)) //month
{
return false; //not a match
}
Regex regex = new Regex("^(apr|jul|oct|jan)$");
string? monthValue = Convert.ToString(values[routeKey]);
if (regex.IsMatch(monthValue))
{
return true; //it's a match
}
else
{
return false; //not a match
}
}
}
Program.cs中注册约束
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRouting(options =>
{
options.ConstraintMap.Add("months", typeof(MonthsCustomRouteConstraint));
});
var app = builder.Build();
Program.cs中使用约束
//Eg: sales-report/2030/apr
endpoints.Map("sales-report/{year:int:min(1900)}/{month:months}", async context
=>
{
int year = Convert.ToInt32(context.Request.RouteValues["year"]);
string? month = Convert.ToString(context.Request.RouteValues["month"]);
if (true)
{
//Do something
}
else
{
//Do something
}
await context.Response.WriteAsync($"sales report - {year} - {month}");
});