【发布时间】:2017-07-25 01:24:13
【问题描述】:
我正在尝试隐藏链接,或者如果用户不是管理员,我将无法访问该页面。我可以在我的控制器中使用此代码来完成后者:
[AuthorizeRoles("Admin")]
public ActionResult Registration()
{
return View();
}
当我尝试使用此代码隐藏链接时:
@if (!Context.User.Identity.Name.IsEmpty())
{
<li id="dd_vehicle" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">VEHICLE <b class="caret"></b></a>
<ul class="dropdown-menu">
@if (ViewContext.HttpContext.User.IsInRole("Admin"))
{
<li id="item_registration">
@Html.ActionLink("Registration", "Registration", "Home")
</li>
}
}
链接被隐藏。但是当我以“管理员”身份登录时,链接仍然没有显示。
这就是我授权属性的方式:
public class AuthorizeRolesAttribute : AuthorizeAttribute
{
private readonly string[] userAssignedRoles;
public AuthorizeRolesAttribute(params string[] roles)
{
this.userAssignedRoles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool authorize = false;
using (var db = new SMBI_DBEntities())
{
var um = new UserManager();
foreach (var roles in userAssignedRoles)
{
authorize = um.IsUserInRole(httpContext.User.Identity.Name, roles);
if (authorize)
return authorize;
}
}
return authorize;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("~/Home/UnAuthorized");
}
}
这是在 LoginView 中:
[HttpPost]
public ActionResult Login(UserLoginView ulv, string returnUrl)
{
if (ModelState.IsValid)
{
var um = new UserManager();
var password = um.GetUserPassword(ulv.LoginName);
if (string.IsNullOrEmpty(password))
{
ModelState.AddModelError("", "Login ID and Pasword do not match.");
}
else
{
if (ulv.Password.Equals(password))
{
FormsAuthentication.SetAuthCookie(ulv.LoginName, false);
return RedirectToAction("Registration", "Home");
}
else
{
ModelState.AddModelError("","Password provided is incorrect.");
}
}
}
return View(ulv);
}
希望您能提供帮助。谢谢。
【问题讨论】:
-
AuthorizeAttribute 不适用于视图端;在这方面它变得有点复杂......网上有一些很好的资源可以在这方面提供帮助。
标签: asp.net-mvc