M
meenakshiBalekar
Modify unwanted HTTP/IIS headers using custom module for .NET Core applications
In modern web development, controlling the HTTP headers of your responses is crucial for security and performance. With traditional ASP.NET framework application, we had the options to alter these headers using the modules and handlers, however when it comes to ASP.NET core, it provides a flexible way to create custom modules( ANCM) that can manipulate these headers. In this blog, we will explore how to create a custom module using middleware in ASP.NET Core to alter unwanted HTTP headers.
In case you are looking to implement such functionality with ASP.NET framework you can refer my previous blog :
Remove unwanted HTTP/IIS headers using custom module for .NET Framework
A custom module in ASP.NET Core is essentially a piece of middleware that intercepts and processes HTTP requests and responses. Middleware components can perform various tasks such as logging, authentication, and, in our case, modifying HTTP headers.
To learn more about custom and managed modules please refer my previous blog:
Manged Modules and Custom Modules in IIS
It is very important to identify how would you like to alter the headers for the ASP.NET core application. The approach that I am sharing here is to get these values altered from the project itself. So if you already have an ASP.NET project created and hosted on IIS, you can make use of it.
Now If I access the application that I have hosted on IIS and see what are the default values present before making the changes I am able to see below headers :
First, create a new ASP.NET Core project. You can use the .NET CLI or Visual Studio for this purpose.
Using .NET CLI:
dotnet new webapi -n CustomHeaderRemoval
cd CustomHeaderRemoval
OR
Using Visual Studio:
I already have an ASP.NET core MVC project created and hosted on IIS that I will be using for this demonstration.
Next, create a middleware class that will handle the removal of unwanted HTTP headers.
Add a new class named “RemoveHeadersMiddleware.cs”:
To use the middleware, it must be registered in the application's request processing pipeline.
Update the Program.cs:
Once the code is modified publish the same to your IIS application folder.
The middleware class created earlier can be used to modify the specified HTTP headers before the response is sent to the client. You can customize the headers and add new values to be displayed back to client.
We cannot remove the server header using ASP.NET core as IIS will set it once it enters IIS pipeline, however on the other hand if you are setting this values using the ASP.NET core project itself, IIS will not override this value hence you can use a different value to be displayed here which will help with enhanced security.
Now post adding the above code and re-deploying the application to IIS, let me browse the application and check the header values :
As you can see here, the server is displaying a new values that is manully set by me at the application code level, also there are few other values that I have added.
Middleware in ASP.NET Core can interfere with incoming requests by executing custom logic at different points in the request pipeline. In our case, the `RemoveHeadersMiddleware` does so by tapping into the `OnStarting` event of the HTTP response. This event allows us to modify the response headers right before they are sent to the client.
If you want to see where this AspNetModule is being invoked you can take a FREB trace and see :
You can see that the AspNetCoreModule(ANCM) is executing the response header alteration.
In this blog, we've covered how to create a custom module in ASP.NET Core to remove unwanted HTTP headers using middleware. We discussed the concept of a custom module, provided detailed steps for creating and registering middleware, and explained how it can interfere with incoming requests. By following these steps, you can enhance the security and performance of your ASP.NET Core applications by managing HTTP headers effectively.
Continue reading...
Table of Contents
- Introduction
- What is a Custom Module?
- Creating a Custom Module Using Middleware
- Interference with Incoming Requests
- Summary
Introduction
In modern web development, controlling the HTTP headers of your responses is crucial for security and performance. With traditional ASP.NET framework application, we had the options to alter these headers using the modules and handlers, however when it comes to ASP.NET core, it provides a flexible way to create custom modules( ANCM) that can manipulate these headers. In this blog, we will explore how to create a custom module using middleware in ASP.NET Core to alter unwanted HTTP headers.
In case you are looking to implement such functionality with ASP.NET framework you can refer my previous blog :
Remove unwanted HTTP/IIS headers using custom module for .NET Framework
What is a Custom Module?
A custom module in ASP.NET Core is essentially a piece of middleware that intercepts and processes HTTP requests and responses. Middleware components can perform various tasks such as logging, authentication, and, in our case, modifying HTTP headers.
To learn more about custom and managed modules please refer my previous blog:
Manged Modules and Custom Modules in IIS
Creating a Custom Module Using Middleware
It is very important to identify how would you like to alter the headers for the ASP.NET core application. The approach that I am sharing here is to get these values altered from the project itself. So if you already have an ASP.NET project created and hosted on IIS, you can make use of it.
Now If I access the application that I have hosted on IIS and see what are the default values present before making the changes I am able to see below headers :
Step 1: Setting Up the ASP.NET Core Project
First, create a new ASP.NET Core project. You can use the .NET CLI or Visual Studio for this purpose.
Using .NET CLI:
dotnet new webapi -n CustomHeaderRemoval
cd CustomHeaderRemoval
OR
Using Visual Studio:
- Open Visual Studio and create a new ASP.NET Core Web API project.
- Name the project " RemoveHeadersUsingHandlers".
I already have an ASP.NET core MVC project created and hosted on IIS that I will be using for this demonstration.
Step 2: Creating the Middleware Class
Next, create a middleware class that will handle the removal of unwanted HTTP headers.
Add a new class named “RemoveHeadersMiddleware.cs”:
Code:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace CustomModuleCore
{
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class RemoveHeadersMiddleware
{
private readonly RequestDelegate _next;
public RemoveHeadersMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
context.Response.OnStarting(() =>
{
context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
context.Response.Headers.Add("Server","newApplication");
context.Response.Headers.Add("X-Content-Type", "nosniff");
context.Response.Headers.Remove("Content-Type");
context.Response.Headers.Remove("Content-Lenght");
return Task.CompletedTask;
});
// Call the next delegate/middleware in the pipeline
await _next(context);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class RemoveHeadersMiddlewareExtensions
{
public static IApplicationBuilder UseRemoveHeadersMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RemoveHeadersMiddleware>();
}
}
}
Step 3: Registering the Middleware
To use the middleware, it must be registered in the application's request processing pipeline.
Update the Program.cs:
Code:
using CustomModuleCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseMiddleware<RemoveHeadersMiddleware>();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Once the code is modified publish the same to your IIS application folder.
Step 4: Removing Unwanted HTTP Headers
The middleware class created earlier can be used to modify the specified HTTP headers before the response is sent to the client. You can customize the headers and add new values to be displayed back to client.
We cannot remove the server header using ASP.NET core as IIS will set it once it enters IIS pipeline, however on the other hand if you are setting this values using the ASP.NET core project itself, IIS will not override this value hence you can use a different value to be displayed here which will help with enhanced security.
Now post adding the above code and re-deploying the application to IIS, let me browse the application and check the header values :
As you can see here, the server is displaying a new values that is manully set by me at the application code level, also there are few other values that I have added.
Interference with Incoming Requests
Middleware in ASP.NET Core can interfere with incoming requests by executing custom logic at different points in the request pipeline. In our case, the `RemoveHeadersMiddleware` does so by tapping into the `OnStarting` event of the HTTP response. This event allows us to modify the response headers right before they are sent to the client.
If you want to see where this AspNetModule is being invoked you can take a FREB trace and see :
You can see that the AspNetCoreModule(ANCM) is executing the response header alteration.
Summary
In this blog, we've covered how to create a custom module in ASP.NET Core to remove unwanted HTTP headers using middleware. We discussed the concept of a custom module, provided detailed steps for creating and registering middleware, and explained how it can interfere with incoming requests. By following these steps, you can enhance the security and performance of your ASP.NET Core applications by managing HTTP headers effectively.
Continue reading...