实施“Down for maintenance”页面

时间:2011-09-28 09:13:54

标签: asp.net-mvc asp.net-mvc-3 maintenance

我知道我们可以简单地使用app_offline.htm文件来执行此操作。

但是如果我的IP是1.2.3.4(例如),我希望能够访问该网站,以便我可以进行最终测试。

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

我们如何在ASP.NET MVC 3中实现它?

4 个答案:

答案 0 :(得分:15)

您可以使用带有IP检查的RouteConstraint的catch-all路径:

确保首先放置离线路线。

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

和约束代码:

public class OfflineRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        // return IpAddress != "1.2.3.4";
    }
}

答案 1 :(得分:14)

Per Max的建议是实际的实施。

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


}

答案 2 :(得分:2)

您可以定义一个全局过滤器,如果它们不是来自您的IP,则会停止所有请求。您可以按配置启用过滤器。

答案 3 :(得分:2)

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