我有一個控制器,它要求一個角色名「管理員」:信息,如果requiment角色
它的控制器的一部分:
[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;
}
}
和定義的ApplicationRoleManager
其繼承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>()));
}
}
如果用戶沒有rolename Admin然後(我不知道如何)被移動到AccountController和方法: public ActionResult Login(string returnUrl)
它的定義:
[HttpGet]
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
現在我想推動信息,以這種方法,如果用戶不是管理員,並給信息「嘿!你不必存取權限頁面的這一部分,請登錄管理員帳戶「然後我擴展了這個方法,這種形式:
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();
}
在我的方式,我知道,所有的控制器,它具有名」 admin 「,fe RolesAdminController,UserAdminController要求Roles =」Admin「,但它不是最酷的方式:/
它工作正常,但是如果用戶(或訪客)沒有訪問權限到控制器?