ASP.NET MVC Ajax Redirect

I’ve had several occasions where I have needed to make an Ajax request to a secure action on the server (i.e. an action that requires the user to be logged in). The problem is…sometimes the user’s session will timeout between the time they access the secure page and the time they make the secure Ajax request. My action notices this and redirects the user to the login page…but if it’s an Ajax request then a simple 302 redirect just won’t work. Here’s a method that will.

public class MyBaseController : System.Web.Mvc.Controller
{
    protected override RedirectResult Redirect(string url)
    {
        return new AjaxAwareRedirectResult(url);
    }
}

public class AjaxAwareRedirectResult : RedirectResult
{
    public AjaxAwareRedirectResult(string url)
        : base(url)
    {
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            string destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);

            JavaScriptResult result = new JavaScriptResult()
            {
                Script = "window.location='" + destinationUrl + "';"
            };
            result.ExecuteResult(context);
        }
        else
            base.ExecuteResult(context);
    }
}

Now you can use the controller’s Redirect() function as usual…and it will automatically detect if it needs to perform a 302 redirect or an Ajax redirect.

First time here? Try these resources...

  1. Best VPN Services
  2. Best WordPress Hostings
  3. Best WordPress Themes
  4. Best WordPress Plugins
  5. Best Gutenberg Block Plugins
  6. Best Email Marketing Plugins
  7. Best WordPress Caching Plugins
  8. Best WooCommerce Plugins
  9. Email Marketing Guide for Beginners
  10. Best Small Business Apps
  11. Best Business Name Generators
  12. Top Plagiarism Checkers
  13. Free Web Hosting Services
  14. Best Online Businesses to Start
  15. Best Online Course Platforms
  16. Best Online Casinos in India
  17. Best Affiliate Marketing Programs
  18. More Resources...

Get useful blogging, marketing and learning resources, delivered to your mailbox. Plus, get regularly updated with extra tools & guides to help you learn, grow and earn better.

Get 17+ exclusive e-books & templates for free, to begin with. 🎁