Have a Asp.NET Core 2.0 application and I would like to map any path that does not start with /api
to just reexecute to the root path. I added the below but doesn't seem to work:
app.MapWhen(
c => !c.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase),
a => a.UseStatusCodePagesWithReExecute("/")
);
Not using MapWhen() and just using app.UseStatusCodePagesWithReExecute("/")
works for all paths not root. Just want to add filtering for all paths not root and not /api
. Any ideas on how to do this?
In a browser with developer tools enabled, make a request to the sample app with the path /redirect-rule/1234/5678 . The regular expression matches the request path on redirect-rule/(. *) , and the path is replaced with /redirected/1234/5678 . The redirect URL is sent back to the client with a 302 - Found status code.
Now, we need to add our custom middleware in the request pipeline by using Use extension method as shown below. We can add middleware using app. UseMiddleware<MyMiddleware>() method of IApplicationBuilder also. Thus, we can add custom middleware in the ASP.NET Core application.
Branch the middleware pipelineMap branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed. The following table shows the requests and responses from http://localhost:1234 using the preceding code. Hello from non-Map delegate.
In addition to path-based mapping, the MapWhen method supports predicate-based middleware branching, allowing separate pipelines to be constructed in a very flexible fashion. Any predicate of type Func<HttpContext, bool> can be used to map requests to a new branch of the pipeline.
Branched pipeline does not work correctly here because you have not added MVC middleware after status code page middleware. Here is the correct pipeline setup:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.MapWhen(
c => !c.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase),
a =>
{
a.UseStatusCodePagesWithReExecute("/");
a.UseMvc();
});
app.UseMvc();
}
Note that middleware order matters here, you should add status code page middleware before MVC.
However using conditional pipeline seems like overkill here. You could achieve your goal with URL Rewriting Middleware:
var options = new RewriteOptions()
.AddRewrite(@"^(?!/api)", "/", skipRemainingRules: true);
app.UseRewriter(options);
app.UseMvc();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With