Q:

How can I return custom http header in asp.net core?

Ciao,
I'm developing a series of microservices with aspnet core. I want to return a custom http header on 500 responses.
I tried to create a custom ASP.NET Core Middleware that update context.Response.Headers property but it works only when the response is 200.
This is my custom middleware:
namespace Organizzazione.Progetto
{
    public class MyCustomMiddleware
    {
        private readonly RequestDelegate _next;

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

        public async Task InvokeAsync(HttpContext context)
        {
            context.Response.Headers.Add("X-Correlation-Id", Guid.NewGuid());
            await _next.Invoke(context);
            return;
        }
    }
}

This is my configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware<MyCustomMiddleware>();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API");
    });
}

How can I return my custom header on a 500 response caused by unhandled exception (or possibly on all the responses)?
Thank you a lot

A:

You have to subscribe on httpContext.Response.OnStarting 
public class CorrelationIdMiddleware
{
    private readonly RequestDelegate _next;

    public CorrelationIdMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        httpContext.Response.OnStarting((Func<Task>)(() =>
        {
            httpContext.Response.Headers.Add("X-Correlation-Id", Guid.NewGuid().ToString());
            return Task.CompletedTask;
        }));
        try
        {
            await this._next(httpContext);

        }
        catch (Exception)
        {
            //add additional exception handling logic here 
            //...
            httpContext.Response.StatusCode = 500;
        }

    }
}

And register it your Starup 
 app.UseMiddleware(typeof(CorrelationIdMiddleware));

