- I have created a middleware using app.Map() that handles a specific route (/hello).
- However, when I add a second middleware using app.Run() that does not check for a specific route.
- It seems to overwrite the response of the first middleware even when a request is made to the /hello route.
I’m confused about why this is happening and how to fix it.
The code is below:
using Microsoft.Extensions.Primitives;
using System.Web;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Map("/hello", async (HttpContext context) => {
context.Response.ContentType = "text/html";
await context.Response.WriteAsync("Hello");
});
app.Run(async (HttpContext context) => {
context.Response.ContentType = "text/html";
await context.Response.WriteAsync("Bye");
});
app.Run();
I tried removing the app.Run() middleware then the specified ‘/hello’ middleware is executing.
But as soon as I add the app.Run() middleware again it then skips the middleware that is mapped to ‘/hello’;
2
Answers
Try switching to
Use
:I guess that the behaviour is due to the fact that the
RunExtensions.Run
adds something called "terminal middleware delegate".Also ASP.NET Core Middleware article can be useful.
You could check the source codes of
RunExtensions.Run()
method hereit adds a middleware like
if you don’t branch the pipeline ,your request would be shortcut
You could try with Guru Stron’s solution or
Or branch the pipeline:
For your requirement
You could check the difference: