Asp.net-Mvc-3

ASP.Net MVC 3 將未經授權的使用者重定向到 loginUrl

  • October 5, 2011

我有一個使用 ASP.Net MVC3 並使用角色成員資格的項目。我在每個控制器中使用授權。例如:

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

如果有人沒有管理員角色,則預設重定向到登錄頁面。如何更改它,使其重定向到 Views/Shared/UnAuthorize.cshtml ?或者如果有人沒有管理員角色,它會顯示消息框(警報)?

提前致謝。

只需更改必須在 web.config 中顯示的頁面(檢查路由是否存在)

<authentication mode="Forms">
 <forms loginUrl="~/UnAuthorize" timeout="2880" />
</authentication>

相反,如果您想為每個角色重定向到特定路徑,您可以使用自己的擴展 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);
 }
}

我解決了我的問題。我只這樣做:

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");

  }
}

並將 MyAuthorize 應用於類或操作:

[MyAuthorize]
public class AdminController :Controller
{
}

而已。

引用自:https://stackoverflow.com/questions/7656163