如何在MVC项目的Web.Config中配置允许访问IP,其余IP显示建设中页面
MVC站点IP访问限制+自定义建设中页面实现方案
方案1:基于web.config + IIS IP安全配置(优先推荐,全站生效)
- 首先确保IIS已安装「IP和域限制」功能:打开IIS管理器,进入对应站点的「功能视图」找到「IP和域限制」,点击右侧「编辑功能设置」,将未授权客户端的访问行为设置为
403 禁止。 - 然后在项目
web.config的system.webServer节点下添加如下配置:
<system.webServer> <security> <!-- IP访问规则配置 --> <ipSecurity allowUnlisted="false"> <!-- 放行指定单个IP --> <add ipAddress="127.0.0.1" allowed="true" /> <add ipAddress="你要放行的公网IP" allowed="true" /> <!-- 如需放行IP段,添加subnetMask参数,示例放行192.168.1.0/24段: <add ipAddress="192.168.1.0" subnetMask="255.255.255.0" allowed="true" /> --> </ipSecurity> <!-- 自定义IP被拒绝时的返回页面 --> <httpErrors errorMode="Custom" existingResponse="Replace"> <remove statusCode="403" subStatusCode="6" /> <error statusCode="403" subStatusCode="6" path="/Home/UnderConstruction" responseMode="ExecuteURL" /> </httpErrors> </security> </system.webServer>
- 最后在
Home控制器下添加UnderConstruction动作方法,对应返回你要展示的站点建设中视图即可。
方案2:基于MVC全局过滤器实现(无需依赖IIS功能,更灵活适配所有部署环境)
如果部署环境没有IIS IP限制功能,可以用代码逻辑实现IP校验:
- 首先在
web.config的appSettings节点添加白名单配置:
<appSettings> <add key="AllowIPList" value="127.0.0.1,你要放行的其他IP" /> </appSettings>
- 新建IP校验全局过滤器:
public class IPCheckFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // 获取请求端IP string clientIP = filterContext.HttpContext.Request.UserHostAddress; // 读取配置的白名单IP List<string> allowIPs = System.Configuration.ConfigurationManager.AppSettings["AllowIPList"].Split(',').ToList(); // IP不在白名单时返回建设中页面 if (!allowIPs.Contains(clientIP)) { filterContext.Result = new ViewResult { ViewName = "UnderConstruction" }; return; } base.OnActionExecuting(filterContext); } }
- 在
App_Start/FilterConfig.cs中注册全局过滤器,让所有请求都走IP校验:
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new IPCheckFilter()); } }
- 在
Views/Shared目录下新建UnderConstruction.cshtml视图,编辑建设中展示内容即可。
*注意:方案2默认仅校验控制器路由请求,如果你需要限制静态资源访问也生效,可结合IIS配置将静态资源请求也走MVC管道即可。
内容的提问来源于stack exchange,提问作者Aero83
相关产品推荐
相关产品推荐

