i have a controller which requirement a role names "Admin":
it's part of controller:
[Authorize(Roles="Admin")]
public class RolesAdminController : Controller
{
public RolesAdminController()
{
}
public RolesAdminController(ApplicationUserManager userManager,
ApplicationRoleManager roleManager)
{
UserManager = userManager;
RoleManager = roleManager;
}
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
set
{
_userManager = value;
}
}
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
and definition of ApplicationRoleManager
which inherit of RoleManager
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole,string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
}
}
if User don't has rolename Admin then (i dont know how) are moved to AccountController and method:
public ActionResult Login(string returnUrl)
It's Definition:
[HttpGet]
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
now I want to push info to this method if User aren't a Admin and give info "Hey! You don't have acces to this part of page, please Login to Admin account", then I expanded this method to this form:
public ActionResult Login(string returnUrl)
{
if (returnUrl != null &&
returnUrl.Contains("Admin") &&
Request.IsAuthenticated &&
!User.IsInRole("Admin"))
{
if (Request.IsAuthenticated)
ViewBag.Info = "Hey! You don't have acces to this part of page, please Login to Admin account";
else
TempData["Info"] = "Hey! You don't have acces to this part of page, please Login to Admin account";
return RedirectToAction("Index", "Home");
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
In my way I know, that all controller, which has name "Admin", f.e RolesAdminController, UserAdminController requirement Roles="Admin", but it isn't the coolest way :/
It works fine, but is other way to define any info if user (or guest) don't have access to controller?