Ron*_*Ron 2 asp.net-mvc attributes custom-attributes asp.net-mvc-3
我有这个自定义授权类来检查用户是否是管理员:
public class IsAdminAttribute : AuthorizeAttribute
{
private datacontext() db = new datacontext();
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
var currentUser = httpContext.User.Identity.Name;
return db.Users.Where(u => u.UserName == currentUser).Where(ut => ut.UserTypeID == 2).Count() == 1 ? true : false;
}
return isAuthorized;
}
}
Run Code Online (Sandbox Code Playgroud)
并在这里使用:
[IsAdmin]
public ActionResult CreateUser()
{
ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeId", "Name");
return View();
}
Run Code Online (Sandbox Code Playgroud)
并且工作正常但在用户未获得授权时将我带回登录页面.我想要发生的是将用户重定向到某处,并弹出错误消息.如何处理拒绝访问事件?
如何处理拒绝访问事件?
只需覆盖HandleUnauthorizedRequest方法并直接返回您喜欢的视图:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new ViewResult
{
ViewName = "Unauthorized"
};
}
Run Code Online (Sandbox Code Playgroud)
这将呈现~/Views/Shared/Unauthorized.cshtml.您还可以将视图模型,母版页等传递给此ViewResult.
| 归档时间: |
|
| 查看次数: |
1548 次 |
| 最近记录: |