ASP.NET Core 6.0 Middleware Not Executing in Custom Order
I've spent hours debugging this and I've been struggling with this for a few days now and could really use some help... I'm stuck on something that should probably be simple. I'm currently working on an ASP.NET Core 6.0 application where I need to implement middleware that modifies the response headers before the response is sent to the client. However, I'm working with issues with the execution order of the middleware. Specifically, my custom middleware doesn't seem to run in the order I expect it to and is not modifying the headers as intended. I have the following middleware setup in my `Startup.cs`: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseMiddleware<CustomHeaderMiddleware>(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` And hereβs what my `CustomHeaderMiddleware` looks like: ```csharp public class CustomHeaderMiddleware { private readonly RequestDelegate _next; public CustomHeaderMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { context.Response.OnStarting(() => { context.Response.Headers.Add("X-Custom-Header", "MyValue"); return Task.CompletedTask; }); await _next(context); } } ``` When I make a request to my API, I do not see the `X-Custom-Header` in the response. I have verified that the request reaches my middleware by placing a breakpoint inside the `InvokeAsync` method, and it does hit that line. However, it seems that the `OnStarting` action is not being executed. Iβve tried repositioning the middleware in the pipeline, ensuring that it is before `UseEndpoints`, but the scenario continues. I have also looked into the ASP.NET Core documentation regarding middleware ordering, but Iβm still exploring. Could there be any other factors at play here, or is there something specific I might be overlooking regarding middleware execution order in this version? Any guidance would be appreciated! What am I doing wrong? For context: I'm using C# on Windows. I'd really appreciate any guidance on this. I recently upgraded to C# latest. This is happening in both development and production on macOS. Thanks for your help in advance!