Take advantage of the HTTP logging middleware in ASP.NET Core to log request and response information with flexibility and ease. Credit: André Gustavo Stumpf When working in web applications in ASP.NET Core, you might often want to log the HTTP request and responses. The HTTP logging middleware included in ASP.NET Core allows you to log request and response data including headers, body, and common properties. This article talks about HTTP logging, why it is essential, and how you can use the HTTP logging middleware in ASP.NET Core 5. To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here. Create an ASP.NET Core MVC 6 project in Visual Studio 2022 First off, let’s create an ASP.NET Core project in Visual Studio 2022. Following these steps will create a new ASP.NET Core MVC 6 project in Visual Studio 2022. Launch the Visual Studio 2022 IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Next. In the “Additional Information” window shown next, select .NET 6.0 (Preview) as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default). Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we won’t be using any of those features here. Click Create. This will create a new ASP.NET Core MVC 6 project in Visual Studio 2022. We’ll use this project to work with HTTP logging in the subsequent sections of this article. What is HTTP logging middleware? The HTTP logging middleware in ASP.NET Core 6 can be used to log requests and responses in your ASP.NET 6 applications. HTTP logging can provide you with logs that include the following: HTTP request information HTTP response information Headers Body Common properties Enable HTTP logging in ASP.NET Core 6 You can enable HTTP logging using the UseHttpLogging extension method as shown in the code snippet given below. app.UseHttpLogging(); In fact HTTP logging is enabled in ASP.NET Core by default. Here is the default code of the Configure method of the Startup class when the project is created. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseHttpLogging(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } Configure HTTP logging middleware in ASP.NET Core 6 The HTTP logging middleware is available by default in ASP.NET Core 6—i.e., you don’t need to install any NuGet packages to work with it. To configure the HTTP logging middleware you need to invoke the AddHttpLogging extension method pertaining to the IServiceCollection interface. The following code shows how you can configure this middleware in the ConfigureServices method of the Startup class. public void ConfigureServices(IServiceCollection services) { services.AddHttpLogging(logging => { //Write your code to configure the HttpLogging middleware here }); services.AddControllersWithViews(); } To configure specific parts of the HTTP request and HTTP response, you can take advantage of the LoggingFields enum as shown in the ConfigureServices method as shown below. httpLogging.LoggingFields = HttpLoggingFields.All; Configure request headers in ASP.NET Core 6 The RequestHeaders collection comprises a set of request headers that can be logged. Note that you can log only those request header values for which the corresponding request header name has been added. The following code snippet illustrates how you can add a request header to the request headers collection of the instance of the HttpLoggingOptions class named httpLogging. httpLogging.RequestHeaders.Add("Request-Header-Demo"); Configure response headers in ASP.NET Core 6 The ResponseHeaders collection comprises a set of response headers that can be logged. You can log only those response header values for which a corresponding response header name has been added. The following code snippet shows how you can add a response header to the response headers collection. httpLogging.ResponseHeaders.Add("Response-Header-Demo"); Specify encoding using MediaTypeOptions in ASP.NET Core 6 You can specify the encoding you would like to use by using the AddText method of the MediaTypeOptions class. Here is a code example that illustrates this: httpLogging.MediaTypeOptions.AddText("application/javascript"); Set request and response body log limit in ASP.NET Core 6 You can also set request and response body size limits using the RequestBodyLimit and ResponseBodyLimit properties of the HttpLoggingOptions class. The following code snippet illustrates how this can be accomplished. httpLogging.RequestBodyLogLimit = 4096; httpLogging.ResponseBodyLogLimit = 4096; The default value for the request and response body limits is 32 KB, or 32768 bytes. You can change it to suit your needs. Complete HTTP logging example in ASP.NET Core 6 The complete source code of the ConfigureServices method is given below for your reference. public void ConfigureServices(IServiceCollection services) { services.AddHttpLogging(httpLogging => { httpLogging.LoggingFields = HttpLoggingFields.All; httpLogging.RequestHeaders.Add("Request-Header-Demo"); httpLogging.ResponseHeaders.Add("Response-Header-Demo"); httpLogging.MediaTypeOptions. AddText("application/javascript"); httpLogging.RequestBodyLogLimit = 4096; httpLogging.ResponseBodyLogLimit = 4096; }); services.AddControllersWithViews(); } Note that using HTTP logging could be detrimental to the performance of an application, particularly when logging the request and response bodies. Hence you should always consider the performance impact when choosing the fields to log. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos