Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement "Down for maintenance" page

I know we could simply use an app_offline.htm file to do this.

But I want to be able access the website if my IP is 1.2.3.4 (for example), so that I can do a final testing.

if( IpAddress != "1.2.3.4" )
{
    return Redirect( offlinePageUrl );
}

How can we implement this in ASP.NET MVC 3?

like image 652
Anwar Chandra Avatar asked Sep 28 '11 09:09

Anwar Chandra


2 Answers

Per Max's suggestion here is an actual implementation.

public class MvcApplication : System.Web.HttpApplication
{

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CheckForDownPage());

    }

    //the rest of your global asax
    //....
}
public sealed class CheckForDownPage : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var path = System.Web.Hosting.HostingEnvironment.MapPath("~/Down.htm");

        if (System.IO.File.Exists(path) && IpAddress != "1.2.3.4")
        {
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.Redirect("~/Down.htm");
            return;
        }

        base.OnActionExecuting(filterContext);
    }


}
like image 58
colemn615 Avatar answered Oct 09 '22 16:10

colemn615


You can use a catch-all route with a RouteConstraint with the IP check:

Make sure you put the offline route first.

routes.MapRoute("Offline", "{controller}/{action}/{id}",
                new
                    {
                        action = "Offline",
                        controller = "Home",
                        id = UrlParameter.Optional
                    },
                new { constraint = new OfflineRouteConstraint() });

and the constraint code:

public class OfflineRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        // return IpAddress != "1.2.3.4";
    }
}
like image 43
Rickard Avatar answered Oct 09 '22 18:10

Rickard