为什么AutogenerateBindingRedirects不适用于Visual Studio 2017中的Web.config

Dan*_*ach 9 c# msbuild asp.net-mvc visual-studio .net-standard-2.0

我引用了一个需要Microsoft.AspNet.WebApi.Client 5.2.4的.Net Standard 2.0库.这有很多依赖关系,需要重定向才能使用更新的版本.

为了避免包/依赖性爆炸,我更新了csproj文件中的第一个PropertyGroup:

<RestoreProjectStyle>PackageReference</RestoreProjectStyle>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
Run Code Online (Sandbox Code Playgroud)

我期待AutoGenerateBindingRedirects阻止我需要更改Web.config以匹配添加的版本.

为什么我仍然需要将绑定重定向添加到我的Web.config来解决程序集冲突?

Dan*_*ach 14

根据https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection,AutoGenerateBindingRedirects似乎不适用于Web项目 .

检查构建的输出显示绑定重定向仅在Web.config中生成.相反,它们位于$(AssemblyName).dll.config中.此文件具有Web.config的原始配置以及绑定重定向.

要将它们放在一起,您可以让MSBuild将生成的配置复制回Web.config.为此,您需要将以下内容添加到csproj:

<Target Name="AfterBuild">
  <Copy SourceFiles="$(TargetDir)\$(AssemblyName).dll.config" DestinationFiles="Web.config" />
</Target>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,还有一些 Visual Studio 集成可以更新 Web.config 中所需的绑定重定向 https://github.com/dotnet/standard/issues/613#issuecomment-354393350 (2认同)

Але*_*кин 6

对于 iis express:在 Web.config 中,将 assemblyBinding 部分替换为

  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <linkedConfiguration href="file:{AssemblyName}.dll.config"/>
  </assemblyBinding>
Run Code Online (Sandbox Code Playgroud)

对于 iis 和 iis Express:

添加到项目 Scripts\CopyRuntimeSection.ps1

param ($from, $to)
$projectPath = Resolve-Path "$($PSScriptRoot)\..\"

$fromFilePath = "$projectPath\$from";
$toFilePath = "$projectPath\$to";

$fromFileXml = [xml](Get-Content -Path $fromFilePath -Raw)
$toFileXml = [xml](Get-Content -Path $toFilePath -Raw)

$toFileXml.configuration.runtime.InnerXml = $fromFileXml.configuration.runtime.InnerXml
$toFileXml.Save($toFilePath)
Run Code Online (Sandbox Code Playgroud)

添加到 csproj

  <Target Name="CopyRuntimeSection" AfterTargets="Build">
    <Exec Command="PowerShell -File Scripts\CopyRuntimeSection.ps1 -from $(OutDir)\$(AssemblyName).dll.config -to Web.config" />
  </Target>
Run Code Online (Sandbox Code Playgroud)