访问DbContext中的HttpContext.Current.User.Identity.Name

本文关键字:User Identity Name Current HttpContext DbContext 中的 访问 | 更新日期: 2023-09-27 18:00:06

我将使用UserName来跟踪Created和Modified字段。为此,我直接在DbContext:中引用了System.Web程序集

public void auditFields()
 {
            var auditDate = DateTime.Now;
            foreach (var entry in this.ChangeTracker.Entries<BaseEntity>())
            {
                switch (entry.State)
                {
                    case EntityState.Detached:
                        break;
                    case EntityState.Unchanged:
                        break;
                    case EntityState.Added:
                        entry.Entity.CreatedOn = auditDate;
                        entry.Entity.ModifiedOn = auditDate;
                        entry.Entity.CreatedBy = HttpContext.Current.User.Identity.Name ?? "anonymouse";
                        entry.Entity.ModifiedBy = HttpContext.Current.User.Identity.Name ?? "anonymouse";
                        break;
                    case EntityState.Deleted:
                        break;
                    case EntityState.Modified:
                        entry.Entity.ModifiedOn = auditDate;
                        entry.Entity.ModifiedBy = HttpContext.Current.User.Identity.Name ?? "anonymouse";
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
}

它是有效的,但它将DbContext与HttpContext紧密耦合,这不是一个好主意,以防我们将DbContext暴露在非web环境中。所以我用这种方式:

public class ApplicationDbContext :
        IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>,
        IUnitOfWork
{
    public ApplicationDbContext()
            : base("ConnectionString")
        {
        }
        public ApplicationDbContext(string userName)
            : base("ConnectionString")
        {
            UserName = userName;
        }
    //Other codes
    public string UserName
        {
            get;
            private set;
        }
    public void auditFields()
    {
            var auditDate = DateTime.Now;
            foreach (var entry in this.ChangeTracker.Entries<BaseEntity>())
            {
                switch (entry.State)
                {
                    case EntityState.Detached:
                        break;
                    case EntityState.Unchanged:
                        break;
                    case EntityState.Added:
                        entry.Entity.CreatedOn = auditDate;
                        entry.Entity.ModifiedOn = auditDate;
                        entry.Entity.CreatedBy = UserName ?? "anonymouse";
                        entry.Entity.ModifiedBy = UserName ?? "anonymouse";
                        break;
                    case EntityState.Deleted:
                        break;
                    case EntityState.Modified:
                        entry.Entity.ModifiedOn = auditDate;
                        entry.Entity.ModifiedBy = UserName ?? "anonymouse";
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
    }
}

在Ioc配置项目中(我在另一个类库中使用structureMap):

ioc.For<IUnitOfWork>()
                   .HybridHttpOrThreadLocalScoped()
                   .Use<ApplicationDbContext>()
                   .Ctor<string>().Is(HttpContext.Current.User.Identity.Name);

但当我运行应用程序时,我会在上面的行中得到这个错误:

Object reference not set to an instance of an object

它似乎无法注入HttpContext。

知道吗?

访问DbContext中的HttpContext.Current.User.Identity.Name

看看这个链接http://techbrij.com/service-layer-entity-framework-asp-net-mvc-unit-testing

作者的解决方案看起来像你的(但他使用了AutoFac而不是StructureMap)。他获得"名字"的"窍门"是Thread.CurrentPrincipal.Identity.Name;

还有一件事,IMHO,我认为您应该使用DateTimeOffSet而不是DateTime作为审核日期。使用DateTimeOffSet,您不会遇到不同时区的问题。像这样:

DateTimeOffSet auditDate = DateTime.UtcNow;

以下内容应该有助于

ASP.NET MVC:HTTPContext和依赖注入

http://mikehadlow.blogspot.com/2008/08/taking-httpcontext-out-of-mvc-framework.html