c# - 当我无权访问 HttpContext 时,如何填充我的审计日志 UserId 字段?

标签 c# entity-framework audit.net

我有一个包含两个项目的解决方案,我的 API 层和我的数据层。

数据层使用 Entity Framework ,不了解 ASP.NET WebApi。

API 层使用 ASP.NET WebApi。

我计划使用 Audit.NET 来审核记录更改。

目前,我已经在我的 API 项目中安装了 Audit.NET、Audit.EntityFramework 和 Audit.WebApi。

我希望使用审核过滤器属性。 (config.Filters.Add(new AuditApiAttribute());)

我的问题是,当我开始填充 EntityLog 对象时,我还想使用当前执行授权操作的用户的 ID 填充 UserId 字段,如果操作是匿名的,则为 null。

作为 Startup.cs 的一部分,我运行此函数来配置 Audit.NET:

private void ConfigureAudit()
        {
            Audit.Core.Configuration.Setup()
                .UseEntityFramework(x => x
                    .AuditTypeMapper(t => typeof(AuditLog))
                    .AuditEntityAction<AuditLog>((ev, entry, entity) =>
                    {
                        entity.UserId = ???;
                        // other fields...
                    })
                    .IgnoreMatchedProperties()
                );
        }

显然此时我不能使用 HttpContext.Current.User.Identity.GetUserId() 因为我不在 Controller 中,而且我没有看到将 UserId 传递到的方法审核事件。

此时如何检索 UserId?

最佳答案

除了史蒂夫的回答,我想你应该可以添加 Custom Field来自OnScopeCreated custom action ,在您的 asp.net 启动逻辑中像这样:

Audit.Core.Configuration.AddCustomAction(ActionType.OnScopeCreated, scope =>
{
    scope.SetCustomField("User", HttpContext.Current.User.Identity.GetUserId());
});

因此,您将在 EF 数据提供程序的 AuditEvent 上拥有该字段,并且应该能够像这样检索:

Audit.Core.Configuration.Setup()
    .UseEntityFramework(_ => _
        .AuditTypeMapper(t => typeof(AuditLog))
        .AuditEntityAction<AuditLog>((ev, entry, entity) =>
        {
            var x = ev.CustomFields["User"];
            ...
        })
        .IgnoreMatchedProperties());

Note: if you are only interested in auditing entity framework DB contexts, you don't need the Audit.WebApi library. That one is for auditing the controller actions.

关于c# - 当我无权访问 HttpContext 时,如何填充我的审计日志 UserId 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58009329/

相关文章:

c# - C# 中的 Postgres 异常

c# - 尝试使用 c# 按两列对 excel 范围进行排序

mysql - DBFirst - 使用 MySQL Connector 和 EF6,如何将时间戳列识别为 StoreGeneratePattern = 已计算?

c# - LINQ 延迟加载和创建新对象

entity-framework - 如何使用 Audit.Net 保存实体关系?

c# - Audit.Net,-即使抛出异常也需要正确的审计

c# - 在 System.Web 中为 Owin 使用 HttpContext 的替代方法

c# - 使用 printf 打印字符串值

c# - 为 Entity Framework Core 中的所有数据库创建并应用迁移