簡體   English   中英

重定向到登錄頁面

[英]Redirect To the log in page

我有一個ASP MVC 5網站,我有多個控制器和視圖,如果未通過if(User.Identity.Is Authenticated)的所有操作,如果未通過身份驗證,如何將用戶芳香地重定向到“登錄”視圖

使用[Authorize]屬性裝飾控制器(如果您希望該控制器內的所有操作都需要認證)或特定操作。 您可以在web.config文件中指定用戶重定向到的登錄URL。

[Authorize]
public class UserController : Controller
{
    public ActionResult Index()
    {
        // Must be authorized
    }

    public ActionResult Users()
    {
        // Must be authorized
    }
}    

public class ProductController : Controller
{
    public ActionResult Index()
    {
        // Doesn't require authorization
    }

    [Authorize]
    public ActionResult Products()
    {
        // Must be authorized
    }
}

進一步閱讀:

http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute(v=vs.118).aspx

對於此任務,您可以使用[Authorize]屬性,該屬性可以在“類”或“操作”級別實現:

[Authorize] 
public class AccountController : Controller
{
    public AccountController () { . . . }

    public ActionResult Register() { . . . }

    public ActionResult Manage() { . . . }

    public ActionResult LogOff() { . . . }
. . .
} 

在上面的實例中,嘗試訪問控制器中的任何操作方法都會將用戶重定向到登錄頁面,然后將進一步重定向到最初請求的操作。

有關如何使用Autohorize屬性的更多信息,請參見MSDN文章 ,該文章已擴展了示例和背景信息。

答案1:

您可以在MVC中使用內置的[Authorize]屬性。

 [Authorize] 
 public class YourController : Controller
 {
   public ActionResult YourAction()
   {

   }
 }

[Authorize]屬性將檢查用戶是否通過身份驗證,如果沒有通過,它將自動將用戶重定向到登錄頁面

答案2:

或者,您可以將自定義過濾器屬性設置為:

 [AuthoriseUser]
 public class YourController : Controller
 {
   public ActionResult YourAction()
   {

   }
 }

public class AuthoriseUserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   // Check user is authenticated 

   // if user is not authenticated then do as :

     filterContext.Result = new RedirectToRouteResult(new
     RouteValueDictionary(new { controller = "Login", action = "Index" }));
}
}

答案3:

正如您在評論部分中所說,您不想在項目中的每個控制器上編寫[Authorize]屬性,那么下面的答案將對您有所幫助:

public class YourController : Controller
{
  protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    //....Check user authentication here           
  }
}

public class MyController : YourController 
{
  public ActionResult Myaction()
  {
    // ...
  }
}

在上面的答案中,您要做的就是創建自定義的基礎控制器YourController ,然后可以在其中放置身份驗證內容,然后Web應用程序中的每個控制器都將繼承YourController而不是內置的基礎Controller class

您可以使用global.asax中的事件對每個請求進行身份驗證和授權。

Application_AuthenticateRequest :當安全模塊已將當前用戶的身份確定為有效時觸發。 至此,用戶的憑證已經通過驗證。

Application_AuthorizeRequest :在安全模塊已驗證用戶可以訪問資源時觸發。

因此,這樣的事情(雖然還不完整)

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
            if (User.Identity.IsAuthenticated)
            {

                // you can re-direct them for example
            }       
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM