I have a CustomeAuthorize action filter that forwards the user to signin page if user is not authenticated. I apply this filter to actions or controllers.
[CustumeAuthorize]
public ActionResult MyAction()
{
//do something here
return View();
}
and the filter looks like this:
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);
}
}
}
Once I assign a value to filterContext.Result, after execution of filter finishes, the execution is (somehow?!) redirected to the SignIn action and MyAction does not execute. This is exactly what I want.
Now say I want to change my CustomAuthorize to authenticate the user against an external website and not my own SignIn action so I am doing something like this:
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);
}
}
}
My problem is that after the execution of the second version of CustomAuthorize filter is finished, execution continues to MyAction which is not what I want! How do I stop the execution of MyAction after filter in this case?
-Update- I just came across a new issue. My MVC application is in an iFrame and I want the Redirect to force the current frame as the main frame after redirection, so I am doing something like:
string url = "http://externalSite.com/login?returnUrl=" + filterContext.HttpContext.Request.RawUrl;
filterContext.HttpContext.Response.Write("<script type=\"text/javascript\">\ntop.location.href = \"" + url + "\";</script>");
Is there a way to pass a javascript to RedirectResult()?
Use the RedirectResult similar to how you were using the RedirectToRouteResult before to replace the result in the filter context.
filterContext.Result = new RedirectResult("http://externalSite.com/login?returnUrl=" + filterContext.HttpContext.Request.RawUrl );
Let me see if I understand - you have an iFrame, and executing an action within this iFrame. You want to redirect to a parent page, not within that iFrame?
If so, just use Redirect(url) in your action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With