Reputation: 2542
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();
}
}
Upvotes: 1
Views: 3693
Reputation: 798
https://learn.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());
Upvotes: 1