简体   繁体   中英

ASP.NET Core, how to check the request for a match with a regular expression?

I need to check the incoming request for a match with the regular expression. If it coincides, then use this route. For this purpose Constraint. But my example does not want to work. RouteBuilder requires a Handler when declaring. And the handler intercepts all requests and does not cause constraints.

Please tell me how to correctly check the incoming request for a match with a regular expression?

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

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

Scroll down to the "MapWhen" section -- I believe this will suit your needs. Using this, you can have the application follow a different pipeline when the request matches certain parameters.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM