You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过IIS或web.config限制单个ASP.NET WEB API方法的IP访问权限

无需修改代码通过IIS/web.config限制单个ASP.NET Web API接口IP访问的配置方案

以下方案完全基于IIS原生功能和web.config配置实现,不需要改动任何应用代码。

前置准备

首先确认IIS已安装「IP和域限制」功能:

  • 打开服务器管理器,进入「添加角色和功能」向导,在「Web服务器(IIS)」-「Web服务器」-「安全性」分类下勾选「IP和域限制」,安装完成后重启IIS服务即可。

核心配置方案

通过location标签精准匹配单个API路径,单独配置IP访问规则,不会影响站点其他接口的访问逻辑。将以下配置添加到站点根目录的web.config文件中:

<configuration>
  <!-- path填写你要限制的单个Web API方法的路由路径,和接口实际访问路径完全匹配即可 -->
  <location path="api/your/target/interface/path">
    <system.webServer>
      <security>
        <!-- allowUnlisted设为false代表仅允许下方列出的IP访问该接口,未列的IP全部拦截 -->
        <ipSecurity allowUnlisted="false">
          <!-- 逐个添加允许访问的单个IP -->
          <add ipAddress="192.168.1.100" allowed="true" />
          <!-- 允许IP段访问的话补充subnetMask参数即可 -->
          <add ipAddress="172.16.0.0" subnetMask="255.255.0.0" allowed="true" />
          <!-- 如果是需要屏蔽特定IP,将allowUnlisted设为true,对应IP的allowed设为false即可 -->
        </ipSecurity>
      </security>
    </system.webServer>
  </location>
</configuration>

异常兼容处理

如果配置后出现配置节锁定报错:

  • 打开IIS管理器,选中对应站点,进入「配置编辑器」,下拉选择system.webServer/security/ipSecurity节点,点击右侧操作栏的「解锁节」后重新配置即可。

如果无法使用IP和域限制功能,可通过URL重写模块实现相同效果,确认安装URL重写模块后添加以下配置:

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Restrict Specific API IP" stopProcessing="true">
          <match url="^api/your/target/interface/path$" />
          <conditions>
            <!-- 规则命中即拦截,以下pattern填写允许访问的IP/IP段正则,negate=true代表不匹配该规则的IP才会触发拦截 -->
            <add input="{REMOTE_ADDR}" pattern="^192\.168\.1\.100$" negate="true" />
            <add input="{REMOTE_ADDR}" pattern="^172\.16\..*$" negate="true" />
            <!-- 如果接口经过反向代理,把{REMOTE_ADDR}替换为{HTTP_X_FORWARDED_FOR}获取真实客户端IP -->
          </conditions>
          <action type="CustomResponse" statusCode="403" statusReason="IP Not Allowed" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

配置完成后直接保存web.config即可生效,无需重启站点或应用池。

内容的提问来源于stack exchange,提问作者srikanth kadem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:48:05