ASP.Net MVC 3重定向UnAuthorized用户不登录loginUrl

nte*_*dka 17 redirect asp.net-membership roles unauthorized asp.net-mvc-3

我有一个使用ASP.Net MVC3并使用角色成员资格的项目.我在每个控制器中使用授权.例如:

[Authorize(Roles = "Administrator")]
    public ActionResult Index(string q, int i)
    {
      return View(model);
    }
Run Code Online (Sandbox Code Playgroud)

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

提前致谢.

nte*_*dka 23

我解决了我的问题.我只这样做:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

public class MyAuthorize : AuthorizeAttribute
{
   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
     //you can change to any controller or html page.
     filterContext.Result = new RedirectResult("/cpanel/roles/unauthorize");

   }
 }
Run Code Online (Sandbox Code Playgroud)

并将MyAuthorize应用于类或操作:

[MyAuthorize]
public class AdminController :Controller
{
}
Run Code Online (Sandbox Code Playgroud)

而已.


Iri*_*dio 12

只需更改必须在web.config中显示的页面(检查路由是否存在)

<authentication mode="Forms">
  <forms loginUrl="~/UnAuthorize" timeout="2880" />
</authentication>
Run Code Online (Sandbox Code Playgroud)

相反,如果您希望重定向到每个角色的特定路径,则可以使用您自己的角色扩展AuthorizeAttribute.像这样的东西(没有经过测试,我写这个给你一个想法)

public class CheckAuthorize : ActionFilterAttribute
{
  public Roles[] Roles { get; set; }
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    //Your code to get the user
    var user = ((ControllerBase)filterContext.Controller).GetUser();

    if (user != null)
    {
      foreach (Role role in Roles)
      {
        if (role == user.Role)
          return;
      }
    }      
    RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
    if user.Role==Role.Administrator
    {
      redirectTargetDictionary.Add("action", "Unauthorized");
      redirectTargetDictionary.Add("controller", "Home");
    }
    else
    {
      redirectTargetDictionary.Add("action", "Logon");
      redirectTargetDictionary.Add("controller", "Home");
    }
    filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于未经身份验证和未经授权的请求,此解决方案将导致重定向到UnAuthorized页面 (2认同)