Home NewsX California Consumer Privacy Act (CCPA) Opt-Out Icon

California Consumer Privacy Act (CCPA) Opt-Out Icon

by info.odysseyx@gmail.com
0 comment 14 views


Fixing Unwanted HTTP/IIS Headers Using Custom Modules for .NET Core Applications

  • introduction
  • What is a custom module?
  • Creating custom modules using middleware
  • Interrupting the receiving request
  • summation

In modern web development, controlling the HTTP headers of a response is crucial for security and performance. While traditional ASP.NET framework applications had the option to change these headers using modules and handlers, ASP.NET Core provides a flexible way to create custom modules (ANCMs) that can manipulate these headers. In this blog, we will see how to create a custom module using: Middleware Change unwanted HTTP headers in ASP.NET Core.

If you want to implement this functionality with ASP.NET framework, please refer to my previous blog.
https://techcommunity.microsoft.com/t5/iis-support-blog/remove-unwanted-http-iis-headers-using-custo…

A custom module in ASP.NET Core is basically a piece of middleware that intercepts and processes HTTP requests and responses. Middleware components can perform a variety of tasks, such as logging, authentication, and in our case, modifying HTTP headers.

Please see our previous blog to learn more about the Customize and Manage modules.

https://techcommunity.microsoft.com/t5/iis-support-blog/manged-modules-and-custom-modules-in-iis/ba-…

It is very important to identify how you want to change the headers of your ASP.NET Core application. The approach I am sharing here is to change these values ​​in the project itself. So if you already have an ASP.NET project created and hosted in IIS, you can leverage that.

Now if you access your IIS hosted application and check what the current defaults are before changing them, you should see the header below:

meenakshiBalekar_8-1725432197330.png

Step 1: Setting up an 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 remove custom header

meenakshiBalekar_5-1725432197326.png

or

Using Visual Studio:

  1. Open Visual Studio and create a new ASP.NET Core Web API project.
    meenakshiBalekar_6-1725432197327.png

  2. Name the project “RemoveHeadersUsingHandlers”.

The ASP.NET core MVC project that we will use for this demo has already been created and hosted on IIS.

Step 2: Create a middleware class

Next, we create a middleware class that removes unwanted HTTP headers.

Add a new class named “RemoveHeadersMiddleware.cs”.

meenakshiBalekar_7-1725432197329.png

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();
        }
    }
}

Step 3: Registering Middleware

To use middleware, it must be registered in the application’s request processing pipeline.

Update Program.cs:

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();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

After modifying the code, publish it to the IIS application folder.

Step 4: Remove Unwanted HTTP Headers

The middleware class we created earlier can be used to modify 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 the client.

You can’t remove the server header using ASP.NET Core because IIS sets it after it enters the IIS pipeline. However, if you set this value using the ASP.NET Core project itself, IIS won’t override it, so you can use a different value to display here, which helps improve security.

Now, after adding the above code and redeploying the application to IIS, let’s browse to the application and check the header values.

meenakshiBalekar_9-1725432197331.png

As you can see here, the server is showing the new values ​​that I manually set at the application code level, along with a few other values ​​that I added as well.

Middleware in ASP.NET Core can intercept incoming requests by executing custom logic at different points in the request pipeline. In our case, `RemoveHeadersMiddleware` does this by tapping into the `OnStarting` event of the HTTP response. This event allows us to modify the response headers just before they are sent to the client.

To find out where AspNetModule is being called, you can perform a FREB trace and see:

meenakshiBalekar_0-1725441923368.png

You can see that AspNetCoreModule(ANCM) is performing the response header change.

In this blog, we covered how to create a custom module in ASP.NET Core to remove unwanted HTTP headers using middleware. We discussed the concept of custom modules, provided detailed steps to create and register a middleware, and explained how you can intercept incoming requests. Following these steps, you can effectively manage HTTP headers to improve the security and performance of your ASP.NET Core applications.





Source link

You may also like

Leave a Comment

Our Company

Welcome to OdysseyX, your one-stop destination for the latest news and opportunities across various domains.

Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

Laest News

@2024 – All Right Reserved. Designed and Developed by OdysseyX