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

.NET 6 Web API如何发布含请求动词过滤的web.config

如何自动为.NET 6 Web API发布生成的web.config添加DELETE动词允许配置

发布.NET 6 Web API时,系统会自动生成web.config,但每次更新应用都需要手动在<requestFiltering>中添加允许DELETE动词的配置,项目内无web.config文件,可通过以下两种方法实现自动化配置:

方法1:添加项目级web.config模板文件

直接在Web API项目根目录创建web.config文件,将自动生成的基础配置与需要的DELETE动词配置合并,发布时系统会以此文件为基础生成最终的web.config,无需手动修改。

完整的web.config内容如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\MyDomain.MySubdomain.MyApp.Web.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess">
        <environmentVariables>
          <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
        </environmentVariables>
      </aspNetCore>
    </system.webServer>
  </location>
  <system.webServer>
    <security>
      <requestFiltering>
        <verbs>
          <add verb="DELETE" allowed="true" />
        </verbs>
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

发布时,ASP.NET Core会自动处理processPath、arguments等动态配置项,核心的DELETE动词允许配置会被保留。

方法2:通过MSBuild任务自动修改发布后的web.config

若不想在项目中保留web.config文件,可在项目的.csproj文件中添加MSBuild目标,在发布完成后自动修改生成的web.config:

<Target Name="AddDeleteVerbToWebConfig" AfterTargets="Publish">
  <!-- 尝试修改已存在的DELETE动词配置 -->
  <XmlPoke XmlInputPath="$(PublishDir)web.config"
           Query="/configuration/system.webServer/security/requestFiltering/verbs/add[@verb='DELETE']/@allowed"
           Value="true"
           Namespaces="&lt;Namespace Prefix='x' Uri='http://schemas.microsoft.com/.NetConfiguration/v2.0'/&gt;" />
  
  <!-- 若未找到对应节点,则添加完整的配置节点 -->
  <XmlPoke Condition="$(LastExitCode) != 0"
           XmlInputPath="$(PublishDir)web.config"
           Query="/configuration"
           InnerXml="$([System.IO.File]::ReadAllText('$(PublishDir)web.config').Replace('&lt;/configuration&gt;', '  &lt;system.webServer&gt;
    &lt;security&gt;
      &lt;requestFiltering&gt;
        &lt;verbs&gt;
          &lt;add verb=&quot;DELETE&quot; allowed=&quot;true&quot; /&gt;
        &lt;/verbs&gt;
      &lt;/requestFiltering&gt;
    &lt;/security&gt;
  &lt;/system.webServer&gt;
&lt;/configuration&gt;'))" />
</Target>

这个任务会先检查web.config中是否已有DELETE动词的配置,若存在则将其设为允许;若不存在,则自动添加完整的<requestFiltering>配置节点。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:27:48