Asp.net-Mvc

實施“停機維護”頁面

  • January 19, 2022

我知道我們可以簡單地使用app_offline.htm文件來執行此操作。

但是如果我的 IP 是 1.2.3.4(例如),我希望能夠訪問該網站,以便我可以進行最終測試。

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

我們如何在 ASP.NET MVC 3 中實現這一點?

您可以使用帶有 RouteConstraint 的包羅萬象的路由和 IP 檢查:

確保首先放置離線路線。

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

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


}

引用自:https://stackoverflow.com/questions/7580911