Write headers after Endpoint middleware?

user3012708

I'm writing custom middleware which requires i attach the results as response headers to a given request. To do this, i've created simple middleware which looks like the following:

public class MyCustomMiddleware
{
  private readonly RequestDelegate _next;

  public MyCustomMiddleware(RequestDelegate next)
  {
    _next = next;
  }

  public async Task InvokeAsync(Microsoft.AspNetCore.Http.HttpContext context, IConfiguration configuration)
  {
    debug.print("I'm before the next piece of middleware");
    
    await _next(context);
    
    Context.Response.Headers.Add("x-special-header-4", "super secret response header");    
  }
}

This of course results in the following exception:

Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.Server.Kestrel.Core.dll System.InvalidOperationException: Headers are read-only, response has already started.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.ThrowHeadersReadOnlyException() at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.System.Collections.Generic.IDictionary<System.String,Microsoft.Extensions.Primitives.StringValues>.Add(String key, StringValues value)

This occurs when i'm using an ActionResult - but also when i've requested something that cannot be routed at all (and would as a result return a 404).

The App Startup order looks like:

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseMiddleware<MyCustomMiddleware>();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

(I have a helper to setup the middleware, which i've omitted from this post, but just adds the custom middleware)

The real aim of the middleware is to measure time taken / other factors, which would need me to 'complete' the request, and then add headers to the response - all without modifying existing user code.

Is there a way that this can be done?

Smartis

You are add the header after calling await _next(context);, which is too late because the response has already started. To fix this issue, you could try the httpContext.Response.OnStarting() delegate:

public class MyCustomMiddleware
{
  private readonly RequestDelegate _next;

  public MyCustomMiddleware(RequestDelegate next)
  {
    _next = next;
  }

  public async Task InvokeAsync(Microsoft.AspNetCore.Http.HttpContext context, IConfiguration configuration)
  {
    Debug.Print("I'm before the next piece of middleware");

    context.Response.OnStarting(state =>
    {
        var ctx = (HttpContext)state;
        ctx.Response.Headers.Add("x-special-header-4", "super secret response header");
        return Task.FromResult(0);
    }, context);

    await _next(context);
  }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Cannot set headers after they are sent to the client in a middleware

Cannot set headers after they are sent to the client using a middleware in nodejs

Modified Req Url in Express middleware ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client

Middleware to protect an endpoint in express

Setting response headers with middleware in Lumen

Write Karate for Pagination endpoint

How to write regex for an endpoint?

Express middleware not called when accessing socketio endpoint

How to run a middleware first in a pipeline but with endpoint metadata?

Python - write headers to csv

Script will not write the headers to a csv

Simpler way to write headers

How to send custom HTTP headers to an endpoint?

Apollo Client not sending headers to API endpoint

How to add cache headers to Strapi API endpoint

How to write to Control Endpoint with PyUSB

How to write to IOHIDDevice endpoint with IOKit

Dynamic headers for Apollo GraphQL (outside of middleware

Control HTTP headers from outer Go middleware

Error when modifying response headers in middleware

How do you add headers to a response with a middleware?

res.headers undefined in middleware of nodeJS typescript

req.headers undefined in middleware of nodeJS typescript

Custom middleware to inject headers from HttpClient response

in Rack middleware how to ignore default headers?

.net core security headers middleware not adding headers to external http requests

Fasthttp + fasthttprouter, trying to write middleware

How to write a middleware in nextjs for serverside

Laravel difference between terminable middleware and after middleware

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive