将MVC中的未经授权的页面访问重定向到自定义视图
我有一个MVC网站,其中的访问基于各种角色.用户登录系统后,他们可以看到导航到他们被授权的页面.但是,某些用户可能仍尝试使用直接URL访问页面.如果是这样,系统将自动将其重定向到登录页面.我想将他们重定向到另一个视图(未经授权),而不是登录页面.
I have an MVC website in which access is based on various Roles. Once a user logs into the system they can see navigation to the pages for which they are authorized. However, some users may still try to access pages using a direct URL. If they do, the system automatically redirects them to the Login Page. Instead of the Login Page I want to redirect them to another view (Unauthorized).
Web.Config具有以下条目:
Web.Config has the following entry:
<customErrors mode="On">
<error statusCode="401" redirect="~/Home/Unauthorized" />
<error statusCode="404" redirect="~/Home/PageNotFound" />
</customErrors>
<authentication mode="Forms">
<forms name="Development" loginUrl="~/Account/Login" cookieless="UseCookies" timeout="120"></forms>
</authentication>
我也在Global.asax.cs中注册了这些路由.
I have registered these routes in Global.asax.cs as well.
routes.MapRoute(
name: "Unauthorized",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Unauthorized", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "PageNotFound",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "PageNotFound", id = UrlParameter.Optional }
);
够了吗?
通过以下更改,它可以正常工作
With following change it is working
public class CustomAuthorize : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//filterContext.Result = new HttpUnauthorizedResult(); // Try this but i'm not sure
filterContext.Result = new RedirectResult("~/Home/Unauthorized");
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (this.AuthorizeCore(filterContext.HttpContext))
{
base.OnAuthorization(filterContext);
}
else
{
this.HandleUnauthorizedRequest(filterContext);
}
}
}
然后按如下所示在Controller或Action上应用:
And then applying on Controller or Action as below:
[CustomAuthorize(Roles = "Admin")]
使用上述方法时,我需要重新访问所有控制器/动作并更改Authorized属性!另外,还需要进行一些测试.
With above approach I need to revisit all the controller/actions and change the Authorized attribute! Also some testing will be needed.
我仍然不确定为什么MVC文档中已解释了Web.Config路由为何不起作用.可能是MVC 4发生了变化!
I am still not sure why Web.Config route not working as same has been explained in MVC Documentation. May be something has changed in MVC 4!