ASP.NET MVC-ユーザーのログインに外部Webサイトを使用するCustomeAuthorizeフィルターアクション

StackOverflow https://stackoverflow.com/questions/835672

質問

ユーザーが認証されていない場合にユーザーをサインインページに転送する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アクションではなく外部Webサイトに対してユーザーを認証するようにしたいので、次のようなことをしています:

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フィルターの2番目のバージョンの実行が終了した後、実行がMyActionに続くことです。この場合、フィルター後にMyActionの実行を停止するにはどうすればよいですか?

-Update-新しい問題に出会いました。私の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)を使用します。

ログインページでjQueryによる判断を追加できます。

$(function () {
        if (window != top) {
            top.location.href = location.href;
        }
    });   

または

アクション「OnActionExecuting」の「filterContext.Result」を編集

filterContext.Result = new ContentResult() { Content = "<script>top.window.location.href='/user/Login'</script>" };
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top