I need to redirect to an external url (let's say "www.google.com") from OnActionExecuting method. Right now I'm using something like this:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var redirectUrl = "www.google.com";
try
{
var isAjaxRequest = filterContext.HttpContext.Request.IsAjaxRequest();
if (isAjaxRequest)
{
filterContext.HttpContext.Response.StatusCode = SessionController.CustomHttpRedirect;
filterContext.HttpContext.Response.StatusDescription = redirectUrl;
filterContext.Result = new JsonResult
{
Data = new { Redirect = redirectUrl },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
filterContext.Result = new RedirectResult(redirectUrl, true);
}
return;
}
else
{
throw new LoggedOutException();
}
}
catch
{
throw new LoggedOutException();
}
}
}
The problem is that it's not redirecting me to "www.google.com" but it's redirecting to "http://localhost:1234/www.google.com" (I try it locally). There is any way to solve this ? Thanks
The problem was verry easy to solve:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var redirectUrl = "http://www.google.com";
try
{
var isAjaxRequest = filterContext.HttpContext.Request.IsAjaxRequest();
if (isAjaxRequest)
{
filterContext.HttpContext.Response.StatusCode = SessionController.CustomHttpRedirect;
filterContext.HttpContext.Response.StatusDescription = redirectUrl;
filterContext.Result = new JsonResult
{
Data = new { Redirect = redirectUrl },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
filterContext.Result = new RedirectResult(redirectUrl, true);
}
return;
}
else
{
throw new LoggedOutException();
}
}
catch
{
throw new LoggedOutException();
}
}
}
All I had to do was that when I assigned the value to "redirectUrl", I had tu put http before wwww. This mus be put if you use a SSL conenction and you're trying to redirect from mvc to another domain.
Instead of using:
filterContext.Result = new RedirectResult("www.google.com", true);
Try the following:
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "External" , ReturnURL = "www.google.com"}));
and in your (Home) controller create an action called (External) and from there redirect to your external url:
public class HomeController : Controller
{
[AllowAnonymous]
public ActionResult External(string ReturnURL){
return Redirect(ReturnURL);
}
}
You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript. see this answer
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