0
我需要檢查傳入的請求是否與正則表達式匹配。如果一致,則使用此路線。爲此目的約束。但我的例子並不想工作。 RouteBuilder在聲明時需要一個Handler。處理程序攔截所有請求並且不會造成約束。ASP.NET核心,如何檢查與正則表達式匹配的請求?
請告訴我如何正確檢查傳入的請求與正則表達式匹配?
配置
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
var trackPackageRouteHandler = new RouteHandler(Handle);
var routeBuilder = new RouteBuilder(app);
routeBuilder.MapRoute(
name: "old-navigation",
template: "{*url}",
defaults: new { controller = "Home", action = "PostPage" },
constraints: new StaticPageConstraint(),
dataTokens: new { url = "^.{0,}[0-9]-.{0,}html$" });
routeBuilder.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
app.UseRouter(routeBuilder.Build());
app.UseMvc();
}
// собственно обработчик маршрута
private async Task Handle(HttpContext context)
{
await context.Response.WriteAsync("Hello ASP.NET Core!");
}
IRouteConstraint
public class StaticPageConstraint : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
string url = httpContext.Request.Path.Value;
if(Regex.IsMatch(url, @"^.{0,}[0-9]-.{0,}html$"))
{
return true;
} else
{
return false;
}
throw new NotImplementedException();
}
}
正則表達式可以簡化爲:@ 「^ {0,} [0-9] - {0,HTML} $」 - > @ 「^ * \ d - * HTML $」 這真的是網址的樣子嗎? example9-whatever.html 。*匹配零和無限次數之間的任何字符(除了行結束符) \ d匹配一個數字(等於[0-9]) - 匹配字符 - 字面上匹配 。*匹配任何在零和無限次之間的字符(除了行結束符) html匹配字母html逐字(區分大小寫) $斷言位置在字符串的末尾,或在字符串末尾的行終止符之前(如果有的話) – wp78de