Search code examples
asp.net.netvisual-studioasp.net-web-apivisual-studio-2022

Cannot publish a blank 64-bit ASP.NET Web API 2 project in Visual Studio 2022


I am having difficulty publishing a new, blank ASP.NET Web API 2 project running on .NET 4.8.

I discovered in an actively developed project, of the same type, that even though the project builds successfully, it cannot be published. After much research and sifting through settings and options, I narrowed it down to this specific issue that can be replicated consistently in a new blank Web API project.

(I can't embed pictures so I have to use links for screenshots.)

If I create a new solution, a new asp.net web application project, untick the configure for https tickbox and select web api as the web application type, and try to publish to a local folder using the default publish settings it works as expected and, after I copy the published files to an IIS Server on my network, the default home page loads.

However, If I set the Projects Debug and Release Platform target to x64, and try to publish, Visual Studio claims the publish succeeded, but if I copy the published files to my IIS Server and browse to the projects url, I get the following error (I realize when I took the screenshots Debug mode was selected but when doing it again in Release identical errors occur).

Server Error in '/' Application.
Could not load file or assembly 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version 4.1.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.
(Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its  dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]dependencies. The located assembly's manifest
definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion! EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion! EnableLog].

Stack Trace:
[FileLoadException: Could not load file or assembly 'Microsoft.CodeDom. Providers.DotNetCompilerPlatform, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +100
System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) +47
System.Type.GetType(String typeName) +42
System.CodeDom.Compiler.Compiler Info.get_IsCodeDomProvider TypeValid() +13
System.Web.Compilation. Compilation Util.GetRecompilationHash (Compilation Section ps) +2915
System.Web.Configuration.CompilationSection.get_RecompilationHash() +93
System.Web.Compilation.BuildManager. CheckTopLevelFiles UpToDate Internal (Int64 cachedHash) +548
System.Web.Compilation.BuildManager. CheckTopLevelFiles UpToDate (Int64 cachedHash) +57
System.Web.Compilation.BuildManager. ExecutePreAppStart() +150
System.Web.Hosting. HostingEnvironment. Initialize (ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +854
[HttpException (0x80004005): Could not load file or assembly 'Microsoft.CodeDom. Providers.DotNetCompilerPlatform, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.Web.HttpRuntime. FirstRequestInit(HttpContext context) +532
System.Web.HttpRuntime. Ensure FirstRequestInit(HttpContext context) +114
System.Web.HttpRuntime. Process Request Notification Private (IIS7Worker Request wr, HttpContext context) +724

Version Information: Microsoft .NET Framework Version: 4.0.30319; ASP.NET Version: 4.8.4110.0

I am not sure if this would impact a potential solution, but my organization requires the publish settings to be the following: (Precompile during publishing, do not allow precompiled site to be updatable, and merge individual folder output to its own assembly)

If I change my publish settings to these, the publish fails with the same error but now in Visual Studio.

Publish has encountered an error.
Build failed. Check the Output window for more details.
A diagnostic log has been written to the following location:
"C:\Users\username\AppData\Local\Temp\tmp2090.tmp"

Log File contents:

6/18/2024 3:12:17 PM
System.AggregateException: One or more errors occurred. ---> Microsoft.WebTools.Shared.Exceptions.WebToolsException: Build failed. Check the Output window for more details.
   --- End of inner exception stack trace ---
---> (Inner Exception #0) Microsoft.WebTools.Shared.Exceptions.WebToolsException: Build failed. Check the Output window for more details.<---

Microsoft.WebTools.Shared.Exceptions.WebToolsException: Build failed. Check the Output window for more details.

===================

Output Window Contents:

Description:
Could not load file or assembly 'WebApplication4' or one of its dependencies. An attempt was made
to load a program with an incorrect format.

Project:
WebApplication4

File:
ASPNETCOMPILER

Line:
0

A different pre-existing 64 bit webapi project that was created months ago does publish successfully today but when examining the csproj files they are nearly identical, the only difference being that the reference entries are listed in slightly different locations within the .csproj file itself. Even in this working, publishable solution, if a new blank webapi project is created, it exhibits the same error if published to a local folder in up-to-date versions of Visual Studio 2017 and 2022 running on the latest build of Windows 10 Pro x64.

In the other projects the library that the error occurs on changes depending on what nuget packages or project references are included. The error only occurs on a single dependency per publish. If there are any project references to, for example, a class library, or a number of extra nuget packages the error will occur one of those instead.

I have tried the following:

  • Updating all nuget packages and leaving them as-is in the new project and neither work.

  • Restarting my PC and restarting Visual Studio.

  • Changing the Bitness of IIS to x64 in the project settings

  • I have done as much research as I can but I only get results for 32bit/64bit library conflicts which may be happening but as far as I have been able to see every setting and every library is 64-bit.

  • Deleting all <assemblyBinding> references in my web.config and running Get-Project -All | Add-BindingRedirect in the Visual Studio Package Manager Console

  • The file path to my solution is only 108 characters long so its not a path-too-long issue

  • Creating a new project on multiple different PCs (not VMs) and also used Visual Studio 2017 and it still didn’t work. For some reason other pre-existing projects don’t have this issue, just any new ones that are made.

At the time of posting I am on the latest version of Visual Studio Professional 2022 (64-bit) 17.10.3, I am also, at the time of posting, on the latest version of Windows 11 Pro Version 10.0.22631 Build 22631


Solution

  • Found the solution. Turns out the .Net compiler path doesn't change from 32 bit if you change the Platform Target to 64 bit.

    First right click the project in the Solution Explorer and select Unload Project, then single click on the project to view the xml of its .csproj file, then within the ProperyGroup tags, add this line (adjust in the future to match the current compiler version):

    <AspnetCompilerPath>$(windir)\Microsoft.NET\Framework64\v4.0.30319</AspnetCompilerPath>
    

    So the end result of your .csproj file should look similar to this (the only lines that must be exactly the same are AspnetCompilerPath and PlatformTarget):

      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
        <AspnetCompilerPath>$(windir)\Microsoft.NET\Framework64\v4.0.30319</AspnetCompilerPath>
        <DebugSymbols>true</DebugSymbols>
        <DebugType>full</DebugType>
        <Optimize>false</Optimize>
        <OutputPath>bin\</OutputPath>
        <DefineConstants>DEBUG;TRACE</DefineConstants>
        <ErrorReport>prompt</ErrorReport>
        <WarningLevel>4</WarningLevel>
        <PlatformTarget>x64</PlatformTarget>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
        <AspnetCompilerPath>$(windir)\Microsoft.NET\Framework64\v4.0.30319</AspnetCompilerPath>
        <DebugSymbols>true</DebugSymbols>
        <DebugType>pdbonly</DebugType>
        <Optimize>true</Optimize>
        <OutputPath>bin\</OutputPath>
        <DefineConstants>TRACE</DefineConstants>
        <ErrorReport>prompt</ErrorReport>
        <WarningLevel>4</WarningLevel>
        <PlatformTarget>x64</PlatformTarget>
      </PropertyGroup>
    

    Then save the file, right click the project in the Solution Explorer and select Reload Project with Dependencies.

    For reference, since this line does not get generated by Visual Studio, to force the compiler to be 32 bit change the path to this (altering the version number to the exact version you have):

    <AspnetCompilerPath>$(windir)\Microsoft.NET\Framework\v4.0.30319</AspnetCompilerPath>
    

    To find the version numbers your Visual Studio installation supports, you can just go to C:\Windows\Microsoft.NET in the File Explorer (or wherever your $(windir) is located) and see what version(s) are installed. There should not be a lot of options to choose from.