This could be tackled using Action Filters
For example, consider what happens when we replace the default FilterConfig.cs file in the App_Start folder of an Asp.Net 4.5.2 MVC project with this:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new RedirectActionFilter());
}
}
public class RedirectActionFilter : IActionFilter
{
static Random rng = new Random();
static bool GetBool() => rng.Next() % 2 == 0;
public void OnActionExecuted(ActionExecutedContext filterContext)
{
if (GetBool())
{
filterContext.Result = new RedirectResult("http://www.bbc.co.uk");
}
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
}
}
Then the OnActionExecuted()
method of our RedirectActionFilter
class gets called before the Asp.Net application responds to the browser. As a result, if GetBool()
returns true then we will redirect to bbc.co.uk otherwise nothing is changed and we would get the normal action result from whichever controller action is handling our request