我最近注意到,当我尝试访问使用自定义属性的控制器操作时,会调用两次GetRolesForUser()。我是Forms的新手并试图完全理解每一件作品。这是典型的行为,还是我错过了什么?
这是我的控制器:
namespace Forms.Controllers
{
public class AdminController : Controller
{
[SiteAuthorization(Roles = "Admin")]
public ActionResult AddUser()
{
return View();
}
}
}
这是我的授权属性:
namespace Forms.Attributes
{
public class SiteAuthorization : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
else if (!Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
{
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/Unauthorized.cshtml"
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
}
这是我的自定义角色提供者:
namespace Forms.Providers
{
public class SiteRoleProvider : RoleProvider
{
private UserRoleRepo _userRoleRepo { get; }
public SiteRoleProvider()
{
_userRoleRepo = new UserRoleRepo(new SMDMContext());
}
// Always called twice (?)
public override string[] GetRolesForUser(string username)
{
return _userRoleRepo.GetUserRolesByUserName(username).ToArray();
}
}
}