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

.NET 8发布配置:如何在发布时注入IIS requestFiltering到web.config

.NET 8 API发布时注入requestFiltering配置到web.config的解决方案

针对你的场景,有几种可行的方法在发布或构建时将requestFiltering配置注入到web.config中:

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

直接在.NET 8 API项目的根目录创建web.config文件,将所需的requestFiltering配置写入其中。发布时,ASP.NET Core会自动将这个文件复制到发布目录,并合并框架生成的默认配置。

示例web.config内容:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483648" /> <!-- 2GB -->
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

方法2:修改FolderProfile.pubxml配置

在现有的FolderProfile.pubxml中添加MSBuild配置,通过web.config变换规则注入目标节点。

修改后的FolderProfile.pubxml示例:

<?xml version="1.0" encoding="utf-8"?>
<Project>
  <PropertyGroup>
    <DeleteExistingFiles>false</DeleteExistingFiles>
    <ExcludeApp_Data>false</ExcludeApp_Data>
    <LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <PublishProvider>FileSystem</PublishProvider>
    <PublishUrl>bin\Release\net8.0-windows8.0\publish\</PublishUrl>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <_TargetId>Folder</_TargetId>
    <!-- 指定发布时使用的变换文件 -->
    <WebConfigTransformFile>$(ProjectDir)Web.Release.config</WebConfigTransformFile>
  </PropertyGroup>
</Project>

然后在项目根目录创建Web.Release.config变换文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483648" xdt:Transform="SetAttributes(maxAllowedContentLength)" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

补充:ASP.NET Core自身请求限制配置

仅修改web.config还不够,ASP.NET Core默认有30MB的请求大小限制,需要在Program.cs中添加对应配置:

builder.Services.AddControllers(options =>
{
    // 设置全局单个请求最大大小为2GB
    options.MaxRequestBodySize = 2147483648;
});

// 也可针对特定Action单独配置
[RequestSizeLimit(2147483648)]
public IActionResult UploadFile()
{
    // 上传逻辑实现
}

内容的提问来源于stack exchange,提问作者bob.mazzo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:37:06