Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIS Custom field logging through HTTP Request in ASP NET Core

I have enabled IIS logging with custom fields for my website.

enter image description here

Previously in MVC, I have used HTTPHandlers and Module to add the above fields to the HTTP Request headers.

web.config:

 <modules runAllManagedModulesForAllRequests="true">
     <!--Handler to process the IIS logs of the site Pagevisit logs-->
    <add name="IISLogger" type="MySite.Website.MvcApplication.Utils.IISLogHandler, MySite.Website.MvcApplication" />
</modules>

IISLogHandler class:

public class IISLogHandler : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        private void context_BeginRequest(object sender, EventArgs e)
        {
              var request = (sender as HttpApplication).Request;
              request.Headers["IIID"] = iiid;
              request.Headers["IID"] = !string.IsNullOrEmpty(customerId) ? 
               customerId : iid;

        }
}

My Generated log:

enter image description here

How do i migrate this to ASPNET Core 2.2.0 ?

like image 952
Dinesh M Avatar asked Sep 26 '19 13:09

Dinesh M


1 Answers

According to the "Migrating the HTTP handlers and modules code to ASP.NET Core middleware" documentation the following template could help with implementation:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

public class LoggingMiddleware
{
    private readonly RequestDelegate _next;

    public string iid = Guid.NewGuid().ToString();
    public string customerId = string.Empty;

    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        
        // Do something with context near the beginning of request processing.

        context.Request.Headers["IIID"] = Guid.NewGuid().ToString();
        context.Request.Headers["IID"] = !string.IsNullOrEmpty(customerId) ? customerId : iid;

        await _next.Invoke(context);

        // Clean up.
    }
}

public static class LoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder)
    {

        return builder.UseMiddleware<LoggingMiddleware>();
    }
}

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseLoggingMiddleware();
    }
}

Also, there is related issue opened on github

like image 50
valerysntx Avatar answered Oct 24 '22 20:10

valerysntx