内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/7447705/asp-net-redirect-to-error-page-if-roles-authorization-fails
我使用MVC 3与表单身份验证.在我的控制器或方法上,我正在做以下操作:
[Authorize (Roles = "developer")]
在这种情况下,我想检查用户是否登录,否则返回到登录页面.但是,如果该用户的“IsInRole”检查返回false,我希望他们去一个不同的视图,例如“未授权”.
什么是最好的方式来完成这样的事情?我希望避免创建一个新的授权属性,所以我没有必要重构整个应用程序中的每个Authorize属性,但如果这是所需的,我将去那条路线.
方法的自定义授权属性可以执行以下任务:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// The user is not authenticated
base.HandleUnauthorizedRequest(filterContext);
}
else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
{
// The user is not in any of the listed roles =>
// show the unauthorized view
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/Unauthorized.cshtml"
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
接着:
[MyAuthorize(Roles = "developer")]
public ActionResult Develop()
{
...
}
代码日志版权声明:
翻译自:http://stackoverflow.com/questions/7447705/asp-net-redirect-to-error-page-if-roles-authorization-fails
以上所述就是小编给大家介绍的《c# – ASP.NET – 如果角色授权失败,重定向到错误页面》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Pro CSS and HTML Design Patterns
Michael Bowers / Apress / April 23, 2007 / $44.99
Design patterns have been used with great success in software programming. They improve productivity, creativity, and efficiency in web design and development, and they reduce code bloat and complexit......一起来看看 《Pro CSS and HTML Design Patterns》 这本书的介绍吧!