DbContext 未更新,但 DB 已更新
本文关键字:DB 已更新 更新 DbContext | 更新日期: 2023-09-27 18:32:53
我有一个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;
}
在用户控制器上,如果我手动更改数据库并刷新页面,我会看到更改。但在此筛选器中,如果我更改数据,则在我回收应用池之前,它永远不会更改。
仅供参考,班级的顶部是这样的:
public class AuthorizeByDbRoleAttribute : AuthorizeAttribute
{
private static ExtVariablesEntities _varDB = new ExtVariablesEntities();
}
如果此筛选器未获取更新的用户信息,则无法阻止用户使用功能(如果已更改且应用池未回收)。
问题是从
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;
}
}
}
这是每次命中此类方法时创建的上下文。