In this article we will create Custom middleware and then we will modify response. Each time when request go back to client then middleware will modify HttpResponse.
Let's consider code 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 midddleware added by devesh"; await _next(context); }
We are going to create custom Middleware and here it is required to inject request delegate in Constructor.
we are adding new header at invoke method. Here we are Modifying httpcontext.
Program.cs -> we need register custom middleware that we created above.
using SampleHttpResponseModify; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); app.UseMiddleware<CustomResponseMiddleWare>(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
We need to use this - > app.UseMiddleware<CustomResponseMiddleWare>();
When we ran application and inspected it found custom added header in response
Now lets try to modify Http header when particular API called
Consider i want to add extra header when we call weather API only then 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 midddleware 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 below condition only, so if below path found then only added 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 additional header is coming.
Another learning point here is sequence of middleware in program.cs
if we move position of UseMiddleware then we will found that this middle ware is not calling due to incorrect positions or order of middleware.
We will not get any response if we add UseMiddleware at below position because it is not going to call.
Conclusion
We have learnt about how to modify http headers using custom middle ware. Keep learning and Keep Enjoying :)
Copyrights © 2024 letsupdateskills All rights reserved