我有一个包含两个项目的解决方案,我的 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/