.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="<Namespace Prefix='x' Uri='http://schemas.microsoft.com/.NetConfiguration/v2.0'/>" /> <!-- 若未找到对应节点,则添加完整的配置节点 --> <XmlPoke Condition="$(LastExitCode) != 0" XmlInputPath="$(PublishDir)web.config" Query="/configuration" InnerXml="$([System.IO.File]::ReadAllText('$(PublishDir)web.config').Replace('</configuration>', ' <system.webServer> <security> <requestFiltering> <verbs> <add verb="DELETE" allowed="true" /> </verbs> </requestFiltering> </security> </system.webServer> </configuration>'))" /> </Target>
这个任务会先检查web.config中是否已有DELETE动词的配置,若存在则将其设为允许;若不存在,则自动添加完整的<requestFiltering>配置节点。
内容的提问来源于stack exchange,提问作者Manteia
相关产品推荐
相关产品推荐

