Implement “Down for maintenance” page

谁说胖子不能爱 提交于 2019-11-29 21:58:29

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

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


}

You can define a global filter that stop all the requests if they don't come from your IP. you can enable the filter by configuration.

I got an infinite loop on colemn615's solution, so I added a check for the offline page.

Also, for later versions of ASP.NET this is split into a FilterConfig.cs file in the App_Start folder.

public class FilterConfig
{

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

    }

    public sealed class CheckForDownPage : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (HttpContext.Current.Request.RawUrl.Contains("Down.htm"))
            {
                return;
            }

            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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!