首页 > 其他分享 >通过Attribute和结果过滤器记录用户操作记录

通过Attribute和结果过滤器记录用户操作记录

时间:2023-04-24 09:56:14浏览次数:31  
标签:MySqlParameter 记录 Attribute request var context 过滤器 new operation

    /// <summary>
    /// 用户操作记录
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class OperationLogAttribute : Attribute, IResultFilter
    {
        public readonly string _description;

        public OperationLogAttribute(string description)
        {
            _description = description;
        }
        /// <summary>
        /// 执行完成
        /// </summary>
        /// <param name="context"></param>
        public async void OnResultExecuted(ResultExecutedContext context)
        {
            try
            {
                context.HttpContext.Request.EnableBuffering();

                var userId = context.HttpContext?.User.GetUserId() ?? -1;
                var userName = context.HttpContext?.User.GetUserName() ?? string.Empty;
                var companyId = context.HttpContext?.User.GetCompanyId() ?? -1;

                var requestInfo = await ReadRequest(context.HttpContext);
                var path = context.HttpContext.Request.Path.Value ?? string.Empty;

                var config = Appsettings.GetConfig<DbConfig>("DbConfig");

                OperationLogInfo operation = new OperationLogInfo(Guid.NewGuid().ToString(), userId, companyId, requestInfo, path, _description, userName, DateTime.Now);
                await StoreReceivedMessage(operation);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        public void OnResultExecuting(ResultExecutingContext context)
        {
        }

        private async Task StoreReceivedMessage(OperationLogInfo operation)
        {
            object[] sqlParams =
        {
            new MySqlParameter("@operation_log_id", operation.OperationLogId),
            new MySqlParameter("@user_id", operation.UserId),
            new MySqlParameter("@user_name", operation.UserName),
            new MySqlParameter("@company_id", operation.CompanyId),
            new MySqlParameter("@request_content", operation.RequestContent),
            new MySqlParameter("@description", operation.Description),
            new MySqlParameter("@request_path", operation.RequestPath),
            new MySqlParameter("@create_time", operation.CreateTime),
            new MySqlParameter("@update_time", operation.CreateTime),
            new MySqlParameter("@is_deleted", operation.IsDeleted),
        };

            var sql =
                $@"INSERT INTO `uc_operation_log`(`operation_log_id`,`user_id`,`user_name`,`company_id`,`request_content`,`request_path`,`description`,`create_time`,`update_time`,`is_deleted`) " +
                $"VALUES(@operation_log_id,@user_id,@user_name,@company_id,@request_content,@request_path,@description,@create_time,@update_time,@is_deleted);";
            var config = Appsettings.GetConfig<DbConfig>("DbConfig");
            var connection = new MySqlConnection(config.ConnectionString);
            await using var _ = connection.ConfigureAwait(false);
            await connection.ExecuteNonQueryAsync(sql, sqlParams: sqlParams).ConfigureAwait(false);
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task<string> ReadRequest(HttpContext context)
        {
            var request = context.Request;

            // request.EnableBuffering(); is necessary for reading the Body stream more than once
            // You need to move the position back to the beginning, otherwise the next pice of middleware
            // that try to get the body will fail to do that, i.e. the position is in the end and thus the 
            // body seems to be empty
            request.Body.Position = 0;
            var buffer = new byte[Convert.ToInt32(request.ContentLength)];
            await request.Body.ReadAsync(buffer, 0, buffer.Length);
            var bodyAsText = Encoding.UTF8.GetString(buffer);
            return bodyAsText;
        }
    }

 

标签:MySqlParameter,记录,Attribute,request,var,context,过滤器,new,operation
From: https://www.cnblogs.com/dayang12525/p/17348519.html

相关文章

  • 远程桌面清空历史记录
    远程桌面清空历史记录: regdelete“HKEY_CURRENT_USER\Software\Microsoft\TerminalServerClient\Default”/va/fregdelete“HKEY_CURRENT_USER\Software\Microsoft\TerminalServerClient\Servers”/fregadd“HKEY_CURRENT_USER\Software\Microsoft\TerminalSe......
  • linux 磁盘空间查看记录
    --查看磁盘空间df-h--查看当前目录所有目录树的大小du-h--查看当前目录下所有子目录大小,depth=0就是指当前目录大小du-h--max-depth=1--查看当前目录下所有文件的大小ls-hl-- 查看mysql安装路径whereismysql--清空文件内容而不删除文件,例如清除文件test.log>tes......
  • 记录一次nodejs操作mongodb报错
    记录一次使用Mongoose操作mongodb报错Mongoose查询回调函数报错BookModel.findOne({name:'Rust'},(err,data)=>{if(err){console.log('读取失败');return;}//输出data变量的值console.log(data);......
  • ARM A7 PMU+perf简单记录
    关键词:pmu,perf等等。简单记录PMU及其内核驱动,内核中perf相关内容,以及两者是如何关联的。然后记录perf应用是如何和PMU硬件关联的,以及如何使用perf查看PMU结果。A7PMU概要PMU作为一个扩展功能,是一种非侵入式的调试组件。对PMU寄存器的访问可以通过CP15协处理器指令和Memory-Ma......
  • 指令记录
    1、点击onClick例子里面是匿名函数的写法exportdefaultclassAppextendsReact.Component{render(){return(<div><input/><buttononClick={()=>{a......
  • 个人对于二分图匹配的学习记录
    二分图匈牙利算法下面展示的是dfs实现的写法。//洛谷P3386二分图最大匹配匈牙利算法#include<bits/stdc++.h>usingnamespacestd;typedeflonglongll;constintN=1505;constintM=50005;inthead[N],eid;structEdge{ intv,w,next;}e[M<<1];v......
  • 记录一次最近遇到的新网络诈骗经历,大家要提高警惕啊
    第一次接到诈骗电话,说是要求修改支付宝信息的,一开始说的确实是很迷惑人,一下子可能没法马上分辨出来,但是到后面说要加QQ操作什么什么的,那肯定就是有严重问题的,因为很多诈骗都是通过QQ来操作的,一听到这个就要警惕了。 他的诈骗流程是这样的:先是说你的支付宝花呗要调整利率,如果不......
  • Buildroot使用记录
     关键词:rootfs、BR2_EXTERNAL等等。 记录buildroot使用各种方法,以及解决的问题。1定制文件系统方法1.1根文件系统覆盖(BR2_ROOTFS_OVERLAY)将BR2_ROOTFS_OVERLAY指向的目录覆盖到output/target根文件系统。还可以通过都好间隔,指定多个目录。配置方式:Systemconfigurati......
  • 修改Git全部Commit提交记录的用户名Name和邮箱Email
    当我们换邮箱了,想把已经提交过的commit的邮箱和用户名改成新的时候。先把本地配置成新的gitconfiguser.name'丁少华'gitconfiguser.email'新邮箱@xx.com'这时候就可以用下面的脚本代码了在项目根目录下创建email.sh写入下面这段代码#!/bin/shgitfilter-branch......
  • C# 多线程记录
    ​ 开发中经常遇到不同的业务访问同一个数据源,而每一个业务的执行流就是一个线程,此时线程一多就会产生多线程最容易遇到的问题——并发。什么是并发?        举个很经典的例子:程序中我们经常要操作一些对象,尤其是内存中的数据             例如当......