Caffeine-Powered Life

MVC Action Result to Redirect to Return URL

It doesn’t take too many MVC applications before you’ll see something like this in your URL bar.

URI with return value

The default MVC project shows you a way to handle it, but it violates DRY if you use the idea of ReturnUrl in more than one place in your application. In my case, I’ve got just that problem. I’ve got an application where you can perform a single activity from multiple places, but I always want to send you back from whence you came. The good news is that this is really easy to accomplish with a custom action result.


public class RedirectToReturnUrlResult : ActionResult

{

  private readonly Func<ActionResult> funcIfNoReturnUrl;



  public RedirectToReturnUrlResult(Func<ActionResult> funcIfNoReturnUrl)

  {

    if (funcIfNoReturnUrl == null) throw new ArgumentNullException("funcIfNoReturnUrl");



    this.funcIfNoReturnUrl = funcIfNoReturnUrl;

  }



  public override void ExecuteResult(ControllerContext context)

  {

      string returnUrl;

      if (TryGetReturnUrl(context, out returnUrl))

      {

        new RedirectResult(returnUrl).ExecuteResult(context);                

      }

      else

      {

        funcIfNoReturnUrl().ExecuteResult(context);

      }

  }



  private bool TryGetReturnUrl(ControllerContext context, out string returnUrl)

  {

      try

      {

        var queryString = context.HttpContext.Request.QueryString;

        returnUrl = queryString["ReturnUrl"];

        return !string.IsNullOrEmpty(returnUrl);

      }

      catch (Exception ex)

      {

        returnUrl = null;

        return false;

      }

  }

}  

The usage is pretty simple, too. We just need to give it a default action result to execute if no “ReturnUrl” query string is found.

See? I told you it was easy.

Comments