Customizing HTTP Headers with Middleware in ASP.NET Core

In this article, we will try to see how we can modify HttpResponse using Custom middleware.

We will create Custom middleware and then we will modify the response. Each time the request goes back to the client the middleware will modify HttpResponse.

public class CustomResponseMiddleWare
{
    private readonly RequestDelegate _next;
    public CustomResponseMiddleWare(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        context.Response.Headers["CustomHeader"] = "This middleware added by Devesh";
        await _next(context);
    }
}

We have created custom middleware and added a new header at the invoke method.

Program.cs

using SampleHttpResponseModify;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Use custom middleware
app.UseMiddleware<CustomResponseMiddleWare>();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Register middleware at the program. cs.

app.UseMiddleware<CustomResponseMiddleWare>();

When we ran the application and inspected it, we found a custom-added header in the response.

Custom

Now let us try to modify the Http header when a particular API is called.

Consider i want to add an extra header when we call weather API only then do we have to add condition on middleware like below.

public class CustomResponseMiddleWare
{
    private readonly RequestDelegate _next;
    public CustomResponseMiddleWare(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        context.Response.Headers["CustomHeader"] = "This middleware added by Devesh Omar";
        if (context.Request.Path.Value == "/WeatherForecast")
        {
            context.Response.Headers["CustomeHeadernparticularRequest"] = "This is header added when this path found";
        }
        await _next(context);
    }
}

We have added the below condition only, so if the below path is found then only add an extra header.

if (context.Request.Path.Value == "/WeatherForecast")
{
    context.Response.Headers["CustomeHeadernparticularRequest"] = "This is header added when this path found";
}

Response on WeatherForcast API. We can see the additional header is coming.

API

Another learning point here is a sequence of middleware in the program.cs

if we move the position of UseMiddleware then we will find that this middleware is not calling due to incorrect positions or order of middleware.

We will not get any response if we add UseMiddleware at the below position because it is not going to call.

 UseMiddleware

Conclusion

We have learned about how to modify http headers using custom middleware. Keep learning and Keep Enjoying.


Similar Articles