创建一个asp.net core 中间件并使用

618 618
C#
sam
sam 2024-05-25 17:42:44

创建一个用于记录用户访问的中间件

代码如下:

public class AdfMonitorMiddleWare
{
    private readonly RequestDelegate _next;
    public AdfMonitorMiddleWare(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        Stopwatch sw = new Stopwatch();
        //获取远程访问IP
        var remoteIp = context.Connection.RemoteIpAddress;

        context.Items["Adf-Ip"] = remoteIp;
        context.Items["Adf-MyData"] = "自定义数据";

        //得到Base64的参数

        Dictionary<string, object> dicQueryParam = new Dictionary<string, object>();
        Dictionary<string, object> dicFormParam = new Dictionary<string, object>();
        string queryParams = "";
        foreach (KeyValuePair<string, StringValues> keyValuePair in context.Request.Query)
        {
            queryParams += "{keyValuePair.Key},{keyValuePair.Value}";
            //if(dicRequestParam.ContainsKey(keyValuePair.Key))
            dicQueryParam[keyValuePair.Key] = keyValuePair.Value;
        }
        context.Items["Adf-QueryParamList"] = dicQueryParam;
        if (!string.IsNullOrEmpty(queryParams))
        {
            Console.WriteLine("当前请求的query参数是:" + queryParams);
        }

        if (context.Request.HasFormContentType)
        {
            string formParams = "";
            foreach (KeyValuePair<string, StringValues> keyValuePair in context.Request.Form)
            {
                formParams += "{keyValuePair.Key},{keyValuePair.Value}";
                dicFormParam[keyValuePair.Key] = keyValuePair.Value;
            }

            context.Items["Adf-FormParamList"] = dicFormParam;

            if (!string.IsNullOrEmpty(formParams))
            {
                Console.WriteLine("当前请求的form参数是:" + formParams);
            }
        }

        //用于记录用户的访问的时间
        //同时将用户访问ip地址
        context.Response.OnStarting(x =>
        {
            sw.Stop();

            string timeInfo = "{sw.ElapsedMilliseconds}ms";
            context.Response.Headers["Adf-ExecuteTime"] = timeInfo;
            return Task.CompletedTask;
        },context);

        //Console.WriteLine("当前访问的ip地址是:{remoteIp}");
        //直接输出 401
        //context.Response.StatusCode = 401;
        //return

        //跳转下一个中间件
        await _next.Invoke(context);
    }


}

功能说明

1、记录所有用户的访问ip地址

2、记录当前用户访问当前页面的时间

3、其他功能根据实际情况可以扩展

中间件注册

app.UseMiddleware<AdfMonitorMiddleWare>();



回帖
  • 消灭零回复