ASP.NET Core,如何检查请求与正则表达式的匹配? [英] ASP.NET Core, how to check the request for a match with a regular expression?

查看:258
本文介绍了ASP.NET Core,如何检查请求与正则表达式的匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

配置

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/zh-cn/aspnet/core/fundamentals/middleware

向下滚动到"MapWhen"部分-我相信这将满足您的需求.使用此方法,可以在请求与某些参数匹配时使应用程序遵循不同的管道.

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

这篇关于ASP.NET Core,如何检查请求与正则表达式的匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆