I recently noticed that GetRolesForUser() is called twice when I try to access a controller action that uses my custom attribute. I'm new to Forms and trying to fully understand each piece. Is this typical behavior or am I missing something?
Here is my controller:
namespace Forms.Controllers
{
public class AdminController : Controller
{
[SiteAuthorization(Roles = "Admin")]
public ActionResult AddUser()
{
return View();
}
}
}
Here is my Authorize Attribute:
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);
}
}
}
}
Here is my custom Role Provider:
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();
}
}
}