California Consumer Privacy Act (CCPA) Opt-Out Icon by info.odysseyx@gmail.com September 4, 2024 written by info.odysseyx@gmail.com September 4, 2024 0 comment 14 views 14 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: 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 or Using Visual Studio: Open Visual Studio and create a new ASP.NET Core Web API project. 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”. 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. 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: 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 Share 0 FacebookTwitterPinterestEmail info.odysseyx@gmail.com previous post Data Intelligence End-to-End with Azure Databricks and Microsoft Fabric next post Explore AI-Enhanced Productivity with Surface Pro 11th Edition & Surface Laptop 7th Edition You may also like 7 Disturbing Tech Trends of 2024 December 19, 2024 AI on phones fails to impress Apple, Samsung users: Survey December 18, 2024 Standout technology products of 2024 December 16, 2024 Is Intel Equivalent to Tech Industry 2024 NY Giant? December 12, 2024 Google’s Willow chip marks breakthrough in quantum computing December 11, 2024 Job seekers are targeted in mobile phishing campaigns December 10, 2024 Leave a Comment Cancel Reply Save my name, email, and website in this browser for the next time I comment.