IIS8.5部署.NET4.6.1 Web API遇Npgsql程序集加载异常求助
This is a classic assembly binding mismatch issue, common when using .NET Standard-based libraries like Npgsql with older .NET Framework versions. Here's a step-by-step solution to get your controller working in production:
1. Remove the System.Net.Sockets NuGet Package
First, undo the mistake of adding a non-4.2.0.0 version of System.Net.Sockets via NuGet. This assembly is already part of the .NET Framework 4.6.1 runtime, so adding it as a NuGet package creates conflicts.
- Open your project's NuGet Package Manager.
- Search for
System.Net.Socketsand uninstall it from your project.
2. Auto-Generate Binding Redirects
Binding redirects tell the .NET runtime to use the framework's installed assembly version instead of the one Npgsql was compiled against. Let Visual Studio handle this automatically:
- Right-click your project in Solution Explorer → Properties.
- Go to the Build tab.
- Scroll to the bottom and check Generate binding redirects on build.
- Rebuild your project. This will update your
web.configwith the correct redirect rules for all dependent assemblies.
3. Manually Add the Redirect (If Auto-Generation Fails)
If the auto-generated redirects don't resolve the issue, add this entry manually inside the <runtime> → <assemblyBinding> section of your web.config:
<dependentAssembly> <assemblyIdentity name="System.Net.Sockets" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" /> </dependentAssembly>
This maps all versions of System.Net.Sockets up to 4.2.0.0 to the version included with .NET 4.6.1.
4. Validate Application Pool Settings
- Ensure your IIS application pool uses .NET Framework v4.0.x (4.6.1 is an in-place update of 4.0; avoid v2.0 entirely).
- You already set "Enable 32-bit applications" to true—confirm all your NuGet packages target x86 or Any CPU to match this setting.
5. Clean, Rebuild, and Redeploy
- Delete the
binandobjfolders from your project to remove stale assembly files. - Rebuild your project in Release mode.
- Republish to your IIS server, ensuring the updated
web.configand all fresh assemblies are deployed.
6. Verify .NET Framework 4.6.1 Installation
A corrupted .NET Framework installation can cause assembly loading issues. Use the .NET Framework Verification Tool to confirm 4.6.1 is properly installed on your production server.
Why This Works
Npgsql is built against .NET Standard, which references newer versions of System.Net.Sockets (like 4.2.0.0). .NET Framework 4.6.1 includes an older version of this assembly, so binding redirects bridge the gap by directing the runtime to use the framework's installed version instead of the one Npgsql expects.
Content of the question comes from Stack Exchange, question author FIL

