DbContext没有更新,但DB是

时间:2016-02-02 21:17:24

标签: c# entity-framework

我有一个MVC 5数据第一个应用程序,我一直在帮助。我让它使用过滤器来确定是否允许AD用户使用某些功能(通过装饰方法/类)。

但是,在更改数据库中的用户信息后,过滤器的上下文仍然具有该用户的旧信息。用户“编辑”'页面保持正确的信息。奇怪。这只发生在过滤器中,而不是在任何控制器中。

这是过滤器:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    if (!base.AuthorizeCore(httpContext)) return false;

    // Get the groups for this authorization (from the decoration attribute)
    var groups = Groups.Split(',').ToList();

    var userDisplayName = string.Empty;

    using (HostingEnvironment.Impersonate())
    {
        // Verify that the user is in the given AD group (if any)
        var context = new PrincipalContext(
            ContextType.Domain);

        var userPrincipal = UserPrincipal.FindByIdentity(
            context,
            IdentityType.SamAccountName,
            httpContext.User.Identity.Name);

        userDisplayName = userPrincipal.DisplayName;
    }

    // check for UserRoles for this 
    var user = _varDB.Users.FirstOrDefault(x => x.UserName == userDisplayName); //< Here is where it gets stale info...
    IList<UserRole> usersRoles = new List<UserRole>();
    if (user != null)
    {
        usersRoles = user.UserRoles.ToList();
    }

    // determine if the user is allowed to see this controller/page
    foreach (var ur in usersRoles)
    {
        if (groups.Contains(ur.RoleName))
        {
            return true;
        }
    }

    return false;
}

在UserController上,如果我手动更改数据库并刷新页面,我会看到更改。但在此过滤器中,如果我更改数据,则在我回收应用程序池之前,它永远不会更改。

fyi,班上最重要的是:

public class AuthorizeByDbRoleAttribute : AuthorizeAttribute
{       
    private static ExtVariablesEntities _varDB = new ExtVariablesEntities();
}

如果此过滤器未获取更新的用户信息,则无法让用户退出或让他们使用功能(如果已更改且应用池未被回收)。

1 个答案:

答案 0 :(得分:1)

问题是继承自AuthorizeAttribute(或我认为的任何属性)的类并不处理上下文。我结束了这样的使用逻辑:

 using (ExtVariablesEntities _varDB = new ExtVariablesEntities())
        {
            // check for UserRoles for this 
            var user = _varDB.Users.FirstOrDefault(x => x.UserName == userDisplayName);

            IList<UserRole> usersRoles = new List<UserRole>();
            if (user != null)
            {
                usersRoles = user.UserRoles.ToList();
            }

            // determine if the user is allowed to see this controller/page
            foreach (var ur in usersRoles)
            {
                if (groups.Contains(ur.RoleName))
                {
                    return true;
                }
            }
        }

这是每次触发此类方法时创建的上下文。

相关问题