I have some common code that runs at the beginning of multiple controller actions. I would like to refactor that code into a static class to promote reuse of that code block.
The code checks for a variable, looks for a cookie and if a condition is met, the code should redirect to another page (controller/action).
The problem is that everything works properly (including the cookie lookup) but the Redirect does not fire. The code passes over the redirect and the redirect never happens.
What is the proper way to redirect in a helper class?
Here is the code now:
This line is not working: myController.HttpContext.Response.Redirect(redirectURL);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyProject.WebUI
{
public static class SessionValidationHelper
{
// helper class to encapsulate common routines to check for missing session data
public static void SessionIdRequired(string id, Controller myController)
{
if (id == null || id == "")
{
// check cookie
if (myController.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("cookiename"))
{
// if a session cookie was found, send to the registration recovery page
string sessionGuidCookieValue = "";
sessionGuidCookieValue = myController.ControllerContext.HttpContext.Request.Cookies["cookiename"].Value;
// check if GUID/SessionID exists in persistent cache
// send to Session Recovery
//myController.HttpContext.Response.RedirectToRoute("SessionRecovery", new { Controller = "SessionRecovery", Action = "Index", id = sessionGuidCookieValue });
string redirectURL = @"~/SessionRecovery/Index/" + sessionGuidCookieValue;
// this code isn't working
myController.HttpContext.Response.Redirect(redirectURL);
}
}
}
}
}
You can create an attribute that is a filter and decorate the action with it:
(I have placed the code you provided in the attribute)
And on your action you do this:
Or if you want to apply it to all actions inside a class:
Or if you want to apply this GLOBALLY (be carefull with this):
In your Application class (the one inheriting
System.Web.HttpApplication, you can do this: