如何在.Net Core 2中为IIS发布定义自定义web.config?

Ale*_*lex 4 iis visual-studio-2017 asp.net-core-2.0

VS将生成(并覆盖)web.config文件,作为发布到IIS的一部分.我需要在文件中包含各种项目(例如扩展文件上传最大大小限制,重定向到HTTPS等).我目前不得不在每次发布后将内容复制并粘贴到文件中.

有没有办法定义Visual Studio在发布IIS的.NET Core 2 Web应用程序时生成的web.config文件的内容?

dav*_*ben 9

不确定你是否解决了这个问题,但是如果有其他人遇到这个问题,我就遇到了这个问题,并最终寻找转换任务的源代码.它包含一些日志记录,所以我运行了dotnet publish一个/v:n参数,它将日志记录详细程度设置为"normal":

dotnet publish src\MyProject -o ..\..\publish /v:n
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我在输出中看到了这个:

_TransformWebConfig:
  No web.config found. Creating 'C:\Development\MyProject\publish\web.config'
Run Code Online (Sandbox Code Playgroud)

即使项目中有web.config.我将web.config "Copy to Output Directory"的属性更改为"Always",现在我项目中的web.config与自动生成的内容合并.

我的csproj现在有这个:

    <None Include="web.config">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
Run Code Online (Sandbox Code Playgroud)

并且发布输出具有:

_TransformWebConfig:
  Updating web.config at 'C:\Development\MyProject\publish\web.config'
Run Code Online (Sandbox Code Playgroud)

注意:如果要发布到已包含web.config的现有目录,它将更新该文件.(即旧的出版物).如果你没有指定输出目录,它将发布到类似的东西/bin/Debug/net471/publish/,其中可能有旧文件.

注意2:您仍然需要Sdk="Microsoft.NET.Sdk.Web"csproj文件中Project节点上的属性,否则它甚至不会在寻找Web.configs.

供参考,这是任务源代码:https: //github.com/aspnet/websdk/blob/master/src/Publish/Microsoft.NET.Sdk.Publish.Tasks/Tasks/TransformWebConfig.cs


Ale*_*lex 5

我终于回到了这个并最终使用了转换:

  1. 在项目根目录下创建 web.release.config 文件

  2. 将该文件的属性设置为 Build Action = None,这样它就不会直接复制到目标文件夹

  3. 使用转换语法来定义需要插入的部分:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <location>
    <system.webServer>
      <security xdt:Transform="Insert">
        <requestFiltering>
          <requestLimits maxAllowedContentLength="209715200" />
        </requestFiltering>
      </security>
      <rewrite xdt:Transform="Insert">
        <rules>
          <rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
            <match url="(.*)" />
            <conditions logicalGrouping="MatchAny">
              <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
            </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
          </rule>
        </rules>
      </rewrite>
      <modules xdt:Transform="Insert" runAllManagedModulesForAllRequests="false">
        <remove name="WebDAVModule" />
      </modules>
    </system.webServer>
  </location>
</configuration>
Run Code Online (Sandbox Code Playgroud)