tp5记录用户的操作日志_在.net core使用中间件记录访问用户的信息日志

e69e2deb7a8b85202ca5411cc0d17fb9.png
定义一个中间件类 来计算http请求的时间
public class ResponseTimeMiddleware{  // Name of the Response Header, Custom Headers starts with "X-"   private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms";  // Handle to the next Middleware in the pipeline   private readonly RequestDelegate _next;  public ResponseTimeMiddleware(RequestDelegate next)  {    _next = next;  }  public Task InvokeAsync(HttpContext context)  {    // Start the Timer using Stopwatch     var watch = new Stopwatch();    watch.Start();    context.Response.OnStarting(() => {      // Stop the timer information and calculate the time        watch.Stop();      var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;      // Add the Response time information in the Response headers.        context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString();      return Task.CompletedTask;    });    // Call the next delegate/middleware in the pipeline      return this._next(context);  }}
  • 定义中间件扩展类MyMiddlewareExtensions
using Microsoft.AspNetCore.Builder;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace MyApi.Middleware{    public static class MyMiddlewareExtensions    {        public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)        {            return builder.UseMiddleware();        }    }}
  • 在Startup中的Configure方法中,注册中间件
     public void Configure(IApplicationBuilder app, IHostingEnvironment env,            Microsoft.AspNetCore.Hosting.IApplicationLifetime lifetime)        {                    //跨域设置            app.UseCors(builder => builder                .AllowAnyOrigin()                .AllowAnyMethod()                .AllowAnyHeader()                .AllowCredentials());            app.UseHttpsRedirection();            app.UseMyMiddleware();//注册中间件            app.UseMvc();               }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值