[英]Custom Authorize Attribute show denied message without routing to controller
In my ASP.NET web application, I'm using CustomAuthorizeAttribute
for access control.在我的 ASP.NET Web 应用程序中,我使用
CustomAuthorizeAttribute
进行访问控制。 So normal way is if the user role is not matched, the user will redirect to a controller and shows the access denied page.所以正常的方法是如果用户角色不匹配,用户将重定向到控制器并显示拒绝访问页面。
Is there any way to do this like if the user role is not matched with authorization, Can't it show the message or alert or something on the view without routing to the controller?如果用户角色与授权不匹配,是否有任何方法可以做到这一点,如果没有路由到控制器,它不能在视图上显示消息或警报或其他内容吗?
This is the Model.这是模型。
public class RoleAuthorize: AuthorizeAttribute {
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
filterContext.Result = new HttpUnauthorizedResult();
} else {
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
controller = "Account", action = "AccessDenied"
}));
}
}
}
Controller checking the authorization控制器检查授权
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[RoleAuthorize(Roles = "1")]
public ActionResult DeleteConfirmed(int id) {
M_Employee m_Employee = db.CreateEmployee.Find(id);
db.CreateEmployee.Remove(m_Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
Editing编辑
I tried doing this我试着这样做
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
filterContext.Result = new HttpUnauthorizedResult();
} else {
System.Web.HttpContext.Current.Session["error"] = "You're not authorize for this action";
}
}
And the page I have modified as我修改的页面为
< div class = "form-actions no-color" > @HttpContext.Current.Session["error"] < input type = "submit"
value = "Delete"
class = "btn btn-default" / > | @Html.ActionLink("Back to List", "Index") < /div>
But it not working.但它不起作用。
You can try this.你可以试试这个。
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
else
{
filterContext.Controller.TempData.Add("RedirectReason", "You are not authorized to access this page.");
filterContext.Result = new RedirectResult("~/Error");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.