I've created a ControllerBase class that overrides the Execute method of the default Controller class. I'm doing this to check the url and pull an associated page from our database. If the page isn't found, I want to redirect to a specific url ("invalid-page"). All is working except the redirect. I've tried to use Response.Redirect("invalid-page"), but it gives me a null reference error. Also tried requestContext.HttpContext.Response.Redirect("invalid-page"), but same error. I'm guessing it doesn't want to let you bypass the MVC process by using a response redirect. And since the override doesn't actually return an ActionResult, I can't just return a Redirect action. Anyone know how I could do a redirect here?
Here's my ControllerBase class:
public class ControllerBase : Controller
{
protected override void Execute(System.Web.Routing.RequestContext requestContext)
{
ViewData.Model = new DynamicPage{ LeftColumnCss = "bg5"};
var friendlyUrl = (string)requestContext.RouteData.Values["friendlyUrl"];
if (friendlyUrl != null && !friendlyUrl.Equals("invalid-page"))
{
var page = PageService.FetchByFriendlyUrl(null, (int?)PageCategoryType.MomMavens, friendlyUrl);
if (page == null)
{
var archivedPage = PageArchiveService.FetchByFriendlyUrl(friendlyUrl);
if (archivedPage != null)
{
page = PageService.FetchById(archivedPage.PageID);
if (page != null)
{
requestContext.HttpContext.Response.Redirect(PageService.GetPageAbsoluteUrl(page));
}
}
}
if (page == null)
{
//This is where I need to figure out how to do a redirect //requestContext.HttpContext.Response.Redirect("invalid-page");
//base.Redirect("invalid-page");
Response.Redirect("contact-us");
return;
}
((DynamicPage)ViewData.Model).CurrentPage = page;
// Allow the page to override the left column class
if (!string.IsNullOrEmpty(page.LeftColumnCssClasses))
{
var classes = page.LeftColumnCssClasses.Split(';');
var index = SubSonic.Sugar.Numbers.Random(0, classes.Length);
if (index == classes.Length)
index--;
((DynamicPage)ViewData.Model).LeftColumnCss = classes[index];
}
}
base.Execute(requestContext);
}
}
EDIT: Somehow I managed to fix it by changing the line:
if (friendlyUrl != null && !friendlyUrl.Equals("invalid-page"))
to...
if (!friendlyUrl.Equals("invalid-page"))
and then using requestContext.HttpContext.Response.Redirect("invalid-page")
, even though that gave me an error before. Not sure why that made a difference. Somehow having pages with blank urls bypass all those checks caused a problem.