首页 文章

ASP.NET Core,如何检查与正则表达式匹配的请求?

提问于
浏览
0

我需要检查传入的请求是否与正则表达式匹配 . 如果一致,则使用此路线 . 为此目的约束 . 但我的例子不想工作 . 在声明时,RouteBuilder需要一个Handler . 处理程序拦截所有请求,不会导致约束 .

请告诉我如何正确检查传入的请求与正则表达式匹配?

configure

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();
    }
}

1 回答

  • 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());
    

相关问题