I was experimenting asp.net core (net9.0) custom middleware with below sample code. In API response I get the text written by middleware but the API response itself is missing. Any insights to help me understand on what is actually happening ?
This is response I get for the API call
Middleware 1. Passing to the next middleware!
Middleware 2. Passing to the next middleware!
Terminal middleware 1!
Middleware 2. Received from previous middleware.
Middleware 1. Received from previous middleware.
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.UseHsts();
// custom nonterminal middleware, only to be added by app.Use();
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Middleware 1. Passing to the next middleware!\r\n");
String? authHeader = context.Request.Headers.Authorization;
if (String.IsNullOrWhiteSpace(authHeader) || !authHeader.ToLower().StartsWith("bearer"))
{
await context.Response.WriteAsync("Middleware 1. Terminating pipeline since auth header is not present.\r\n");
}
else
{
// Call the next middleware in the pipeline
await next.Invoke();
await context.Response.WriteAsync("Middleware 1. Received from previous middleware.\r\n");
}
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Middleware 2. Passing to the next middleware!\r\n");
// Call the next middleware in the pipeline
await next.Invoke();
await context.Response.WriteAsync("Middleware 2. Received from previous middleware.\r\n");
});
// custom terminal middleware, only to be added by app.Run();
app.Run(async context =>
{
await context.Response.WriteAsync("Terminal middleware 1!\r\n");
});
app.Run(async context =>
{
// never reached since terminal Middleware 1 will not forward to this middleware
await context.Response.WriteAsync("Hello from terminal middleware 2!\r\n");
});
app.MapGet("/", () => "Hello World!");
app.Run();