13

我已经为我的网站启用了带有自定义字段的 IIS 日志记录。

在此处输入图像描述

之前在 MVC 中,我使用 HTTPHandlers 和 Module 将上述字段添加到 HTTP 请求标头中。

网络配置:

 <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 类:

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;

        }
}

我生成的日志:

在此处输入图像描述

如何将此迁移到 ASPNET Core 2.2.0?

4

1 回答 1

1

根据"Migrating the HTTP handlers and modules code to ASP.NET Core middleware" 文档,以下模板可以帮助实施:

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

此外,在 github 上打开了相关问题

于 2021-08-26T20:21:55.483 回答