Implement "Down for maintenance" page

Anwar Chandra picture Anwar Chandra · Sep 28, 2011 · Viewed 12.4k times · Source

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?

Answer

Rickard picture Rickard · Sep 28, 2011

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";
    }
}