Din*_*h M 10 c# middleware iis-logs httprequest asp.net-core
我为我的网站启用了带有自定义字段的IIS日志记录。
以前在MVC中,我曾使用HTTPHandlers和Module将上述字段添加到HTTP Request标头中。
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>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我生成的日志:
如何将其迁移到ASPNET Core 2.2.0?
根据"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();
}
}
Run Code Online (Sandbox Code Playgroud)
另外,github上也打开了相关问题
归档时间: |
|
查看次数: |
104 次 |
最近记录: |