runtime: Could not load file or assembly 'netfx.force.conflicts'

I’ve compiled project with new release of VS 2015.3. Installed .Net Core 2.0 SDK. Project is a pretty old Asp.Net web application, where all project deps were converted to .Net Standard.

No on every page load I get

[BadImageFormatException: Cannot load a reference assembly for execution.]

[BadImageFormatException: Could not load file or assembly 'netfx.force.conflicts' or one of its dependencies. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +225
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +110
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +22
   System.Reflection.Assembly.Load(String assemblyString) +34
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +48

[ConfigurationErrorsException: Could not load file or assembly 'netfx.force.conflicts' or one of its dependencies. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +771
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +256
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +58
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +236
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +69
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +139
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +172
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +912

[HttpException (0x80004005): Could not load file or assembly 'netfx.force.conflicts' or one of its dependencies. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +534
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +111
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +718

How to resolve this?

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 26
  • Comments: 86 (26 by maintainers)

Most upvoted comments

I found a solution: delete the bin folder under your web application and rebuild them all.

Welcome to DLL hell. This is what happens when Microsoft parrots the Java Maven world. One of the things I have always hated about Java. .NET used to be superior, but, now we are in DLL hell thanks to the advent of NuGet.

This issue also happens suddenly to me in a non-Core .NET 4.6.2 / 4.7 project (i.e. full .NET Framework) together with Visual Studio 2017 Community Edition.

My guess is that some NuGet package I’m using was updated and (accidentially) brings in .NET Core.

Maybe unrelated: I’m also getting tons of exclamation marks in my references list after upgrading all NuGet packages to their latest version:

image

When having maximum build log verbosity, I find lines like:

Primary reference “System.Security.Cryptography.X509Certificates, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”. (TaskId:21) 1> Resolved file path is “C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\ref\System.Security.Cryptography.X509Certificates.dll”. (TaskId:21) 1> Reference found at search path location “{RawFileName}”. (TaskId:21) 1> This reference is not “CopyLocal” because at least one source item had “Private” set to “false” and no source items had “Private” set to “true”. (TaskId:21) 1> The ImageRuntimeVersion for this reference is “v4.0.30319”. (TaskId:21)

I have no idea why the “packages.config” reference to this “System.Security.Cryptography.X509Certificates” assembly does not actually fetch it from the NuGet-downloaded “packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461” folder but instead looks in the MSBuild folder.

Awesome support, @ericstj, thanks a lot. That actually did the trick! (Although I have no idea what this actually does 😕)

If the workaround will be no longer necessary in the future, will it do any harm to leave it inside my CSPROJ files?


Steps to solve

The linked solution says to add the following to the CSPROJ file:

<Target Name="UpdateOriginalItemSpecs" AfterTargets="ResolveAssemblyReferences">
    <ItemGroup>
        <ReferencePath>
            <OriginalItemSpec>%(ReferencePath.FileName)</OriginalItemSpec>
        </ReferencePath>
    </ItemGroup>
</Target>

Sometimes more was necessary to add to the CSPROJ file. My working CSPROJ ended up with the following added:

<Target Name="UpdateOriginalItemSpecs" AfterTargets="ResolveAssemblyReferences">
  <ItemGroup>
    <ReferencePath>
      <OriginalItemSpec>%(ReferencePath.FileName)</OriginalItemSpec>
    </ReferencePath>
  </ItemGroup>
</Target>
<Target Name="ReplaceNetFxNetStandardRefWithLib" AfterTargets="ImplicitlyExpandNETStandardFacades">
  <ItemGroup>
    <Reference Remove="@(_NETStandardLibraryNETFrameworkReference)" Condition="'%(FileName)' != 'netfx.force.conflicts'" />
    <Reference Include="@(_NETStandardLibraryNETFrameworkLib)">
      <Private>true</Private>
    </Reference>
  </ItemGroup>
</Target>
<Target Name="RemoveNetFxForceConflicts" AfterTargets="ResolveAssemblyReferences">
  <ItemGroup>
    <ReferencePath Remove="@(ReferencePath)" Condition="'%(FileName)' == 'netfx.force.conflicts'" />
  </ItemGroup>
</Target>
<Target Name="RemoveNetFxForceConflicts" BeforeTargets="BuiltProjectOutputGroupDependencies">
  <ItemGroup>
    <ReferencePath Remove="@(ReferencePath)" Condition="'%(FileName)' == 'netfx.force.conflicts'" />
  </ItemGroup>
</Target>

What also helped me was to switch the projects back from .NET 4.7 to something lower like 4.6.2.

This also requires to edit all “packages.config” files and replace “net47” with “net462” then issue the following in the Package Manager Console of VS:

Update-Package -Reinstall

And finally, I also needed to delete the /bin and /obj folder as well as the temporary ASP.NET folders in e.g. “C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\temp”.

Based on https://github.com/dotnet/sdk/pull/1612, I guess this fix didn’t make it in time for 15.4.

The assemblies are coming from “C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft.NET.Build.Extensions” (vs2017) or “C:\Program Files (x86)\MSBuild\Microsoft\Microsoft.NET.Build.Extensions” (older VS’s) or “C:\Program Files\dotnet\sdk\2.0.0\Microsoft\Microsoft.NET.Build.Extensions” (dotnet cli).

The assemblies under the “ref” folders are the smaller versions: they are reference assemblies that do not contain any implementation, only the metadata for our public API. The assemblies in the “lib” folder are the actual implementation assemblies.

When you rebuild an underlying project, without building the web project, it copies the “wrong” versions of the assemblies to the web bin directory. Confirmed this by diffing against a copy of “known-good” bin directory. Because the web project doesn’t build, the workaround ref/lib fix target doesn’t execute.

Yes, that’s the bug that @BillHiebert is fixing in the web project system. It’s copying the reference assemblies when it shouldn’t because it doesn’t notice that they set copylocal=false. Despite the fix going into the web project system we still need to make a change to the targets that are adding the reference assemblies because the project-system update won’t go everywhere and we’re finding more cases of other desktop build tools that try to load the reference assemblies for execution.

To get around this, I manually adjusted the binding redirects in the web.config for several assemblies to newVersion=“4.0.0.0”, the version in the GAC

That will break anyone who’s depending on API that was added in the later versions. The ones in the GAC will be missing the API or typeforwards that were added to the assemblies.

We’re working making a better fix for this, see: https://github.com/dotnet/corefx/issues/23830.

After installing vs2107 15.3 I had this problem with ASP.net MVC app==> Could not load file or assembly ‘netfx.force.conflicts’

to resolve:

delete /bin and /out AND very important DELETE %temp%\Temporary ASP.NET

Thanks for the confirmation @Quppa. I’m closing this issue as there isn’t any work left to track.

@Quppa Yes, it is pretty unacceptable IMHO that Microsoft does not provide installers for older versions of Visual Studio such as 15.2. Way to go “software as a service.” I wasted about a day and a half trying to downgrade after running into a critical error. I tried System Restore also. That resulted in a VS that displayed a blank white screen. I had to undo the System Restore and there is no way to upgrade 15.0 to a version less than 15.3. Most likely, I will downgrade a project I just upgraded to EF Core 2 back to 1.1 again given the complete fiasco that how DLLs work now. I thought problems like the JSON config file fiasco would be solved by now. Apparently, I need a second computer to test all this stuff in advance. Release software for .NET Core is beta at best.

@UweKeim I’ve got the same issue. I’m having loads of The referenced component 'System.Security.Cryptography.X509Certificates' could not be found. Draycir.Approvals.WebApi and its suggesting tons of redirects.

We’re seeing the same issue. We have .NET 4.7 ASP.NET projects referencing .NET Standard 1.6 projects, all using PackageReference. Deleting bin and obj and rebuilding gets rid of the warning, but I’m then greeted with a different YSOD:

[FileLoadException: Could not load file or assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]

[FileLoadException: Could not load file or assembly 'System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]

This may be a separate issue, but it wasn’t happening with Visual Studio 15.2 and the associated tooling.

For our build server I’ve ‘fixed’ the issue by copying across the MSBuild directory from 15.2, since there seems to be no way to downgrade through the installer.

Updated to VS 15.4 and this is still persisting for me. Solution has a total of 20 projects (class libraries, asp.net mvc / web api, console apps, MS Test projects) - all targeting 4.6.2. Yellow Screen of Death appears when debugging asp.net applications. Typically it references a faliure to find the correct version of netfx.force.conflicts or System.Xml

None of the above fixes have worked for me. The only way I can get the web apps to debug is to run a Clean, then have a powershell command that nukes obj and bin directories along with the IIS Express temp folder. Rebuilding and debugging then usually works.

This is a total pain in the a$$ - it’s killing productivity. It only started after running a solution wide nuget update - how am I supposed to figure out which one of the 160+ packages is the root cause for this?

After applying workaround to each project in solution work when build all web projects. When build any library project override System.* assemblies in bin folder of all web project in the solution and error BadImageFormatException on random System.* assembly

Does anyone know if Microsoft is planning on releasing an official fix for this stuff so that developers don’t have to muck around in the project files? It makes me wonder, does Microsoft bother testing on .NET Framework, or, do they just assume that we are all just going to immediately switch to .NET Core. Hello, Microsoft, if you’re listening, most of your customers are still on .NET Framework. It wouldn’t hurt if you tested on that platform to make sure things work once and awhile. This is the same thing that happened with the JSON project file. Personally, I am amazed that this is still an issue as of 2.0. I just have to keep reminding myself that for all practical purposes, this is beta software. It will probably be another year or so before it is stable and close to a 1.0 product that is usable.

do you know what ‘netfx.force.conflicts’ is?

Its a facade that references every contract assembly that is inbox in desktop: https://github.com/dotnet/corefx/blob/master/src/netfx.force.conflict/ref/netfx.force.conflicts.csproj

It is only a ReferenceAssembly and should never make it to the application’s output directory. There is no corresponding lib for this assembly since it has no typedefs and will never appear in the runtime assembly closure.

   System.Reflection.Assembly.Load(String assemblyString) +34
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +48

[ConfigurationErrorsException: Could not load file or assembly 'netfx.force.conflicts' or one of its dependencies. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +771
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +256
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +58
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +236

Looking at that callstack it appears that Asp.NET may be doing something unusual, it looks to me like it is trying to load reference assemblies for execution. That’ll fail whenever there is any assembly with the ReferenceAssemblyAttribute. @pranavkm @DamianEdwards does this look right to you?

This might help ignoring netfx.force.conflicts. b.t.w. on VS 2017 15.4.3 and 15.4.2 the yellow icons should have been solved.

 <compilation debug="true" targetFramework="4.7" >
       <assemblies>
         <remove assembly="netfx.force.conflicts"/>
       </assemblies>
     </compilation>

I’ve investigated and lost lots of time on the issue too. It basically starts, when MSBuild thinks you have a dependency on .NetStandard. That could be any Nuget Package, such as microsoft.aspnet.Odata 6.x or any package that references .NetStandard. As soon as this get’s into ‘true’, there is a boolean setting here C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\Microsoft.NET.Build.Extensions.NETFramework.targets See inside (cannot copy the file contents here, since github comment editor filters the xml out)!

Now what happens, MSBuild ‘thinks’ it is copying and loading the correct version into your build, but in fact, the Nuget verion, might be -newer- than the ones from here (Microsoft.NET.Build.Extensions see above). What happens next is, I think, 3 things.

  1. your assembly redirects in your app.config /web.config has the wrong redirect versions, for which Visual Studio WILL warn, and thus the yellow icons. However, VS 2017 15.3 and higher, cannot really solve the hell (even if you let VS ‘solve’ the versions).
  2. The .Netstandard 2.0 libraries are not really net standard 2.0 libraries but 1.6.x libraries
  3. The compiler cannot fix the correct signatures anymore and matches with netfx.force.conflicts.dll and copies that invalid dll into the bin path

You can set the boolean switch on ‘false’ but now the .NEtstandard facade does not exist in your bin folder, and thus, the NuGet libraries that depend on them, will fail. In short, a total mess Microsoft!

https://social.msdn.microsoft.com/Forums/en-US/51dc828b-43ca-4177-b68e-7a6a9cf81db5/ms-build-extensions-file-corrupt-my-bin-web-api-folder?forum=msbuild

Sure did - but I found the cause and added it as an edit to my original comment. Thanks for replying.

@andrii-litvinov We had this same issue. When you rebuild an underlying project, without building the web project, it copies the “wrong” versions of the assemblies to the web bin directory. Confirmed this by diffing against a copy of “known-good” bin directory. Because the web project doesn’t build, the workaround ref/lib fix target doesn’t execute.

To get around this, I manually adjusted the binding redirects in the web.config for several assemblies to newVersion="4.0.0.0", the version in the GAC. I found these one by one by loading the site and updating for the assembly which caused the error. In our case it was 5 assemblies, but I expect this may differ based your project:

  • System.Reflection
  • System.Runtime
  • System.Runtime.Extensions
  • System.Runtime.InteropServices
  • System.Xml.ReaderWriter

Visual Studio gives warnings about those binding redirects, but I have instructed my team to ignore them for now.

The fix can’t ship instantly. I’m providing workarounds that folks can use now while the team which owns the component has the chance to investigate and fix. We’re already looking at putting a fix for this in from two different angles: web project system which is copying files incorrectly and the SDK which is adding this file NETFramework projects, including those on previous VS versions which cannot get the fix to the web project system. I’m sorry if that’s not clear from this issue which is in the library repo: we are planning to ship fixes.

I’ll also note that this bug is a result of work done specifically to bring .NETStandard2.0 back to .NET Framework 4.6.1 as part of this 2.0 release. Its a brand new feature. We hear you about .NET Framework, we’re trying to bring more things to desktop: this is one of them. I agree that the test coverage of desktop is lacking: that needs to improve. Desktop is especially difficult since we’re trying to reach our customers across many VS versions that have many very different projects and technologies consuming this tooling. I do want to thank folks like @alfeg, @UweKeim, @mscrivo, and @pranavkm and others for helping us to get to the bottom of this and fix it. Its exactly this type of effort that can help us improve these sorts of things in the future.

@mscrivo is that a web project or something different? I want to make sure we are able to track down all the cases where this is happening.

I have a workaround for folks hitting this, add the following to your project file, or some common targets file imported by your project file if you prefer:

<Target Name="RemoveNetFxForceConflicts" AfterTargets="ResolveAssemblyReferences">
  <ItemGroup>
    <ReferencePath Remove="@(ReferencePath)" Condition="'%(FileName)' == 'netfx.force.conflicts'" />
  </ItemGroup>
</Target>

I’ve also filed a bug in the sdk repo to track getting this fix in the product: https://github.com/dotnet/sdk/issues/1509

My findings / try-n-error cleaning - just updated VS.NET - did not change framework version (.NET 4.7) nor update nuget or anything else:

  • Delete the bin folder(s) - maybe even the ASP.NET shadow copy %temp%\Temporary ASP.NET Files
  • Remove all dependentAssembly from web.config and then:
  • Do a Update-Package -reinstall in the Package Manager Console
  • 2 x click in the warnings dialog (I now have 80 (!!) bindingRedirect in my web.config)
  • I removed all the yellow references manually / deleted them - build and runtime worked fine with them though (?!)
  • I had to manually remove NETStandard.Library from 2 projects by editing the .csproj files. These projects had nuget Microsoft.CodeAnalysis.Common - might (have been) the culprit.
  • A re-publish now shows an additional 64 DLL files added to the solution - most of them shadow/redirect DLLs and one new netstandard.dll

Nice to have: A way to convert existing projects to use PackageReference instead of packages.config - maybe that could possible help the nuget DLL hell a bit 😃 Also, that little warning message during build with the 2 x click functionality - i think that should be an in-your-face prompt! 😃

@UweKeim see the linked issue I opened in the SDK repo (with workaround). I think this is what you are hitting.

/cc @dsplaisted This is the built-in netstandard support for .NETFramework. For net461 and later you no longer need packages to get netstandard support, we put it in the build system.

@Quppa to fix those warnings you should apply all of the suggested binding redirects. That should resolve the YSOD. For projects with web.config this means double clicking the warnings in the error window and letting VS modify your web.config. For app.config you can enable automatic bindingRedirects and they’ll be automatically written to app.config on build.

@UweKeim check your error list’s warning tab. You may see the same redirect warnings that @Quppa was mentioning and applying the redirects will fix them. edit: you may be hitting https://github.com/dotnet/sdk/issues/1499

So I’ve just encountered this issue after trying to add an internal .net core library to a .net 4.6 project. Have absolutely zero idea what to do in this case, have tried some of the fixes above, but nothing seems to be getting me through.

Is there a concise summary of what’s happening and what needs to be done here? Completely hit a wall here and need to resolve.

I am getting a similar issue with a web application project when I try and do a release build - but strangely not when I do a debug build. I’ve tried the various fixes listed above with no joy. Any suggestions? An attempt was made to load an assembly with an incorrect format: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\ref\netfx.force.conflicts.dll Edit: Found the cause… the release version must have been trying to generate a serialization assembly whereas the debug didn’t (both set to auto) https://github.com/dotnet/standard/issues/418

I have investigated more and found that it works fine when I build web project. But when I build one of the projects that it references after build of web project I get the error from above. In particular it makes my tests fail. Any clue on what can it be? I have applied the fix to all the projects in the solution. And All are using PackageReference for NuGet.

Hitting the same problems, The work around is to remove that file. Any chance of a status update on a permanent fix?

You can try this instead, it’s possible the previous target isn’t being run in some cases since there is more than one target that sets ReferencePath (Eg: DesignTimeRAR).

<Target Name="RemoveNetFxForceConflicts" BeforeTargets="BuiltProjectOutputGroupDependencies">
  <ItemGroup>
    <ReferencePath Remove="@(ReferencePath)" Condition="'%(FileName)' == 'netfx.force.conflicts'" />
  </ItemGroup>
</Target>

If that doesn’t work then we might have more than one case of tooling copying non-copy-local references to the output.

The workaround does not work. I’ve added it to all our projects with the {349c5851-65df-11da-9384-00065b846f21} project type guid and it still ends up in our bin folders. I’m going to try adding it to all our projects next.

I have the “RemoveNetFxForceConflicts” workaround in my web projects but this error keeps coming back every 30 minutes or so. I have to constantly delete \bin\ and rebuild.

Got it, thanks.

@UweKeim glad that worked for you. The thing its doing is tricking the IDE into thinking that the references that replaced your project entries actually came from the project. Hopefully we’ll get the SDK to fix this bug. FWIW the same bug was present even in the project.json nuget stuff but it was less common. The workaround is mostly harmless, but it could also cause the same issue if you happened to have full-path references in the project itself. If we wanted it to be more scoped we could refine the workaround to not have that behavior.

@pranavkm I see the repro. The msbuild log doesn’t show the copy happening. Indeed build of the SLN from msbuild does not repro. Build from VS does: 100% for me. I procmon’ed it and I see the copy happening from the devenv.exe process (not msbuild, though I do see the MSBuild traces so I’m certain its an out-of-proc build). I’m not getting a good callstack out of procmon so will need to debug VS to get the actual culprit. I suspect some ASP.NET component responsible for debugging the site, so would be happy if someone can step in and help from that side.

@chris31389 Is there a way to get the actual error message behind a yellow exclamation mark ⚠️ in Solution Explorer?

@ericstj do you know what ‘netfx.force.conflicts’ is?