Reputation: 719
I have an attribute [RedirectSSL] that may or may not redirect a http-request to a corresponding https-request under some conditions:
[RedirectSSL]
public class ControllerA : Controller(){
public ActionResult MethodA()
{
if (SomeExpression)
return RedirectToAction("MethodB", "ControllerA");
return RedirectToAction("MethodC", "ControllerA");
}
public ActionResult MethodB()
{
return View();
}
public ActionResult MethodC()
{
return View();
}
}
The problem with this code is that it throws a System.Web.HttpException whenever the RedirectSSL-attribute has called the Response's Redirect() method before the RedirectToAction() is returned. The solution is to encapsulate the redirects within an
if(!Response.IsRequestBeingRedirected){ ... }
But what should be returned if this evaluates to false? An EmptyResult() would do I guess, but I don't like the way the code looks as it isn't clear to me by looking at it that it will redirect the client. Any thoughts?
Thanks in advance!
Upvotes: 1
Views: 834
Reputation: 5632
ActionFilter
helps you decide if an action can be executed or not. You can bypass the action altogether by providing an ActionResult
from the filter. Something along the lines of
public class RedirectSSLAttribute:ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(!filterContext.HttpContext.Request.IsSecureConnection)
{
filterContext.Result = new RedirectResult("your url");
return;
}
base.OnActionExecuting(filterContext);
}
}
Upvotes: 1