2017-09-16 36 views
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,} [0-9] - {0,HTML} $” - > @ “^ * \ d - * HTML $” 这真的是网址的样子吗? example9-whatever.html 。*匹配零和无限次数之间的任何字符(除了行结束符) \ d匹配一个数字(等于[0-9]) - 匹配字符 - 字面上匹配 。*匹配任何在零和无限次之间的字符(除了行结束符) html匹配字母html逐字(区分大小写) $断言位置在字符串的末尾,或在字符串末尾的行终止符之前(如果有的话) – wp78de

回答

1

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware

向下滚动到 “MapWhen” 部分 - 我相信,这将满足您的需求。使用它,你可以让应用程序在请求匹配某些参数时遵循不同的管道。

 app.MapWhen(
      context => ... // <-- Check Regex Pattern against Context 
      branch => branch.UseStatusCodePagesWithReExecute("~/Error") 
      .UseMvc(routes => 
      { 
       routes.MapRoute(
        name: "default", 
        template: "{controller=SecondController}/{action=Index}/{id?}") 
      }) 
      .UseStaticFiles());