Asp.net-Mvc

ASP.NET MVC - CustomeAuthorize 過濾器操作使用外部網站登錄使用者

  • August 14, 2017

我有一個 CustomeAuthorize 操作過濾器,如果使用者未通過身份驗證,它會將使用者轉發到登錄頁面。我將此過濾器應用於操作或控制器。

[CustumeAuthorize]
public ActionResult MyAction()
{
  //do something here
  return View();
}

過濾器看起來像這樣:

public class CustomAuthorizeAttribute : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {

       if (!currentUserIsAuthenticated)
       {

           filterContext.Result =
               new RedirectToRouteResult(
                   new RouteValueDictionary{{ "controller", "Account" },
                                                { "action", "SignIn" },
                                                { "returnUrl",    filterContext.HttpContext.Request.RawUrl }
                                               });
       }
       else
       {
           base.OnActionExecuting(filterContext);
       }
   }
}

一旦我為 filterContext.Result 分配了一個值,在過濾器執行完成後,執行(不知何故?!)重定向到 SignIn 操作並且 MyAction 不執行。這正是我想要的。

現在說我想更改我的 CustomAuthorize 以針對外部網站而不是我自己的 SignIn 操作對使用者進行身份驗證,所以我正在做這樣的事情:

public class CustomAuthorizeAttribute : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {

       if (!currentUserIsAuthenticated)
       {
            filterContext.HttpContext.Response.Redirect("http://externalSite.com/login?returnUrl=" + filterContext.HttpContext.Request.RawUrl);
       }
       else
       {
           base.OnActionExecuting(filterContext);
       }
   }
}

我的問題是,在執行完第二版 CustomAuthorize 過濾器後,繼續執行 MyAction,這不是我想要的!在這種情況下,如何在過濾後停止執行 MyAction?

**-更新-**我剛遇到一個新問題。我的 MVC 應用程序位於 iFrame 中,我希望重定向在重定向後強制目前幀作為主幀,所以我正在做類似的事情:

string url = "http://externalSite.com/login?returnUrl=" + filterContext.HttpContext.Request.RawUrl;
filterContext.HttpContext.Response.Write("<script type=\"text/javascript\">\ntop.location.href = \"" + url + "\";</script>");

有沒有辦法將 javascript 傳遞給 RedirectResult()?

使用類似於之前使用 RedirectToRouteResult 的 RedirectResult 來替換過濾器上下文中的結果。

filterContext.Result = new RedirectResult("http://externalSite.com/login?returnUrl=" + filterContext.HttpContext.Request.RawUrl );

讓我看看我是否理解 - 你有一個 iFrame,並在這個 iFrame 中執行一個動作。您想重定向到父頁面,而不是在該 iFrame 內?

如果是這樣,只需在您的操作中使用 Redirect(url)。

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