【问题标题】:Audit.NET Adding UserName to AuditLog when logging EF but can't reach HttpContextAudit.NET 在记录 EF 时将用户名添加到 AuditLog 但无法访问 HttpContext
【发布时间】:2021-11-28 00:46:49
【问题描述】:

上下文

我正在使用 .Net Framework 4.8 在 MVC5 应用程序中尝试连接 Audit.Net。

数据提供者:EntityFramework

输出:宇宙

DI 提供者:Autofac

问题

我尝试了以下回调来尝试将用户名写入 AuditEvent。

Configuration.AddOnCreatedAction(scope =>
{
    var username = HttpContext.Current.User.Identity.GetUserId();
    scope.SetCustomField("User2", username);
});
Configuration.AddOnSavingAction(scope =>
{
    var username = HttpContext.Current.User.Identity.GetUserId();
    scope.SetCustomField("User2", username);
});
Configuration.AddOnSavingAction(scope =>
{
    var user = AutofacDependencyResolver.Current.Resolve<IPrincipal>();
    scope.SetCustomField("User2", user.Identity.GetUserId());
});

这些用于对 dbContext.SaveChanges() 的同步调用,当调用 SaveChangesAsync() 时,我无法访问当前的 HttpContext,因为它始终为空。

有什么建议吗?

【问题讨论】:

    标签: c# autofac audit.net


    【解决方案1】:

    键(可能有助于搜索字词)是async。快速搜索async httpcontext mvc 可以让我们找到this existing question,其中包含大量有关async/awaitHttpContext 使用情况的信息。

    超短版本:在 MVC 中,HttpContext 在线程同步上下文中被携带(这也是文化和其他线程设置被携带的地方),但从线程中取出该上下文是昂贵的线程所以默认是不这样做您需要明确启用它才能工作。

    Here's a blog article explaining the various knobs you can turn in web.config to get it to work 但最终结果基本上是确保设置了 &lt;httpRuntime targetFramework="4.5" /&gt;(嗯,将该值设置为 4.5 或更高)。

    如果 已经 设置了,那么......也许还有其他事情在起作用,比如调用设置了 ConfigureAwait(false),因此它不会返回到具有 @987654331 的线程上下文@。但是,httpRuntime 标志很可能会修复它。

    【讨论】:

    • 非常感谢@travis-illig。虽然它没有解决问题,但我离我更近了一步,我学到了很多东西。运行时已经是 4.8。 Audit.NET 的代码没有 configureawait 会导致上下文丢失。我丢失上下文的 Db Save 是在保存用户时。使用Microsoft.AspNet.Identity.UpdateAsync() 这个函数可能是罪魁祸首。所以我现在将继续讨论这个话题。
    猜你喜欢
    • 2020-11-16
    • 2019-12-23
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2014-05-17
    • 2018-05-04
    • 1970-01-01
    相关资源
    最近更新 更多