asp.net-mvc-3 – ASP.Net MVC 3重定向未经授权的用户不登录Url

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – ASP.Net MVC 3重定向未经授权的用户不登录Url前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用ASP.Net MVC3并使用角色成员的项目。我在每个控制器中使用授权。
例如:
  1. [Authorize(Roles = "Administrator")]
  2. public ActionResult Index(string q,int i)
  3. {
  4. return View(model);
  5. }

如果有人没有管理员的角色,那么默认情况下将重定向登录页面。如何更改它,所以它会重定向到Views / Shared / UnAuthorize.cshtml?或者如果有人没有管理员的角色,它会显示消息框(警报)?

提前致谢。

解决方法

只需更改必须在web.config中显示页面(检查路由是否存在)
  1. <authentication mode="Forms">
  2. <forms loginUrl="~/UnAuthorize" timeout="2880" />
  3. </authentication>

相反,如果您要为每个角色重定向到特定的路径,则可以使用自己的方式来扩展AuthorizeAttribute。这样的东西(没有测试,我写这个给你一个想法)

  1. public class CheckAuthorize : ActionFilterAttribute
  2. {
  3. public Roles[] Roles { get; set; }
  4. public override void OnActionExecuting(ActionExecutingContext filterContext)
  5. {
  6. //Your code to get the user
  7. var user = ((ControllerBase)filterContext.Controller).GetUser();
  8.  
  9. if (user != null)
  10. {
  11. foreach (Role role in Roles)
  12. {
  13. if (role == user.Role)
  14. return;
  15. }
  16. }
  17. RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
  18. if user.Role==Role.Administrator
  19. {
  20. redirectTargetDictionary.Add("action","Unauthorized");
  21. redirectTargetDictionary.Add("controller","Home");
  22. }
  23. else
  24. {
  25. redirectTargetDictionary.Add("action","logon");
  26. redirectTargetDictionary.Add("controller","Home");
  27. }
  28. filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
  29. }
  30. }

猜你在找的asp.Net相关文章