c# - 有没有办法在 .Net MVC 中实现用户操作的审计跟踪

标签 c# asp.net .net asp.net-mvc

我是 .Net MVC 新手。我设计了一个使用 Ado.Net CRUD 操作而不使用 Entity Framework 的 Web 应用程序。我在互联网上搜索了如何在 .Net MVC 应用程序上实现审计跟踪,但我得到了在 EF 应用程序上实现审计跟踪的结果。有人可以提供任何资源引用或示例吗?先谢谢各位了!

最佳答案

I need to capture the user visited page and action performed on that page

您可以实现一个 HttpModule 来记录 .NET MVC 应用程序中所有访问过的页面。

通过 HttpModule,您可以访问所有请求/响应属性,包括 header 、Cookie、FormData 参数。

namespace MyApplication
{
    public class DatabaseAuditHttpModule : IHttpModule
    {
        private class Properties
        {
            public string Url { get; set; }
            public string HttpMethod { get; set; }
            public int StatusCode { get; set; }
            
            // add other important HTTP properties
        }
        
        public void Init(HttpApplication context)
        {
            context.BeginRequest += BeginRequest;
            context.EndRequest += EndRequest;
        }

        private void BeginRequest(object sender, EventArgs e)
        {
            HttpContext ctx = HttpContext.Current;
            var request = ctx.Request;

            var requestHeaders = request.Unvalidated.Headers;
            var requestFormData = request.Unvalidated.Form;

            var properties = new Properties
            {
                Url = request.Url.ToString(),
                HttpMethod = request.HttpMethod
            };

            ctx.Items["X-Properties"] = properties;
        }


        private void EndRequest(object sender, EventArgs e)
        {
            HttpContext ctx = HttpContext.Current;

            // get the properties for the current HTTP request
            Properties properties = (Properties)HttpContext.Current.Items["X-Properties"];

            properties.StatusCode = ctx.Response.StatusCode;
            
            // TODO:
            // log these values in the database
        }

        public void Dispose()
        {

        }
    }
}

Global.asax中注册HttpModule:

namespace MyApp.Mvc
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            
        }
 
        // register DatabaseAuditHttpModule
        public static DatabaseAuditHttpModule AuditHttpModule = new DatabaseAuditHttpModule();
 
        public override void Init()
        {
            base.Init();
 
            AuditHttpModule.Init(this);
        }
    }
}

记录存储过程执行示例:

public class DatabaseService
{
    public static async Task ExecuteStoredProcedureAsync(string connectionString, string storedProcedureName, ILogger logger)
    {
        logger.LogTrace($"'{storedProcedureName}' Stored Procedure executing");
        long totalDuration = 0;

        Stopwatch sw = new Stopwatch();
        sw.Start();

        using(var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            
            sw.Stop();
            totalDuration += sw.ElapsedMilliseconds;

            logger.LogTrace($"connection.Open() Duration:{sw.ElapsedMilliseconds}");

            sw.Restart();
            
            using (var command = SqlCommand(storedProcedureName, connection))
            {
                command.CommandType = CommandType.StoredProcedure;

                using (var reader = await command.ExecuteReaderAsync())
                {
                    sw.Stop();
                    totalDuration += sw.ElapsedMilliseconds;

                    logger.LogTrace($"'{storedProcedureName}' Stored Procedure ExecuteReader Duration:{sw.ElapsedMilliseconds}");

                    sw.Restart();

                    do
                    {
                        while (await reader.ReadAsync())
                        {
                            // read the data
                        }

                    } while (await reader.NextResultAsync());
                }

                sw.Stop();
                totalDuration += sw.ElapsedMilliseconds;

                logger.LogTrace($"'{storedProcedureName}' Stored Procedure executed. Duration:{totalDuration}");

                return result;
            }
        }
    }
}

关于c# - 有没有办法在 .Net MVC 中实现用户操作的审计跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62654001/

相关文章:

c# - json 与 xamarin android 解析

c# - 从控制台\Web 应用程序记录到 Azure 诊断

.net - 您的小型网络开发公司设置是什么?

.net - 匿名 Oracle 参数?

c# - 为用户提供发送未捕获异常错误报告的选项

c# - 从 CSV 文件中读取数据

c# - 如何从网址下载所有文件?

asp.net - 只读 session 可写

javascript - 如何正确使用JavaScriptStringEncode()方法?

asp.net - 如何在gridview中包含DatePicker文本框?