Search code examples
.net-corevisual-studio-codeasp.net-core-mvccsproj

.NET Core 3 - SmtpClient fails in MVC project with PublishTrimmed=true


Specifics:

  • dot net core 3 mvc project using SmtpClient
  • publishing as single file, trimmed (PublishTrimmed true in csproj file)

Steps: Create new dotnetcore 3 project:

dotnet new mvc

In HomeController.cs, add a blank SmtpClient command under Index():

public IActionResult Index()
        {
            using (SmtpClient client = new SmtpClient())
            {
            }
            return View();
        }

Modify csproj file for single file,trimmed,output runtime. csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <PublishSingleFile>true</PublishSingleFile>
    <PublishTrimmed>false</PublishTrimmed>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
  </PropertyGroup>


  <ItemGroup>
  </ItemGroup>

</Project>

Publish command:

dotnet publish

Run, then navigate to /

Error message:

System.TypeLoadException: Could not load type 'System.Net.Mail.SmtpClient' from assembly 'Microsoft.AspNetCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
at PubTrimmedSmtpIssue.Controllers.HomeController.Index()

If I remove or switch PublishTrimmed to false in csproj, the project runs properly.


Any ideas as to why PublishTrimmed is causing errors?


Solution

  • Apparently the trimmer is trimming too much in your case.

    You can customise the trimming behaviour in the csproj file:

    <ItemGroup>
      <TrimmerRootAssembly Include="System.Net.Mail" />
    </ItemGroup>