BinaryFormatter serialization disabled in .NET 5

August 25th 2023 .NET

During the upgrade of an ASP.NET Core Web API application from .NET Core 3.1 to .NET 6 I stumbled across a breaking change that only manifested itself at run time despite a pretty good test coverage.

The tests all passed, but for the ASP.NET Core Web API application executing the same code, the BinaryFormatter serialization methods were disabled and threw a NotSupportedException:

System.NotSupportedException: 'BinaryFormatter serialization and deserialization are disabled within this application. See https://aka.ms/binaryformatter for more information.'

To be fair, there were also compiler warnings, but I've seen too many projects with lots of warnings not being fixed and in such a case a few additional ones like these can easily end up being overlooked:

'BinaryFormatter.Serialize(Stream, object)' is obsolete: 'BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.'

'BinaryFormatter.Deserialize(Stream)' is obsolete: 'BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.'

In .NET 7, these same warnings were changed to errors, which I like better. You can't overlook them.

The recommended way to fix the issue is to stop using BinaryFormatter and find alternative ways to implement your functionality. That's what I did in the project I was upgrading. BinaryFormatter was used for creating deep clones of objects, so I reimplemented the functionality differently.

As a temporary workaround, you can add the EnableUnsafeBinaryFormatterSerialization property to your project file to disable the warning or error and make the BinaryFormatter work again:

<EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>

To see the behavior of BinaryFormatter in different .NET versions, you can check a sample project I pushed to my GitHub repository. A different .NET version is used in each commit.

Although, most of the things just work when upgrading a project from an older to a newer .NET version, there are still some breaking changes like the BinaryFormatter one I stumbled upon, and you should always test everything thoroughly before deploying the application to production after the upgrade. It's also a good idea to not have any compiler warnings in your project, as this way any new warnings won't get lost among the existing ones.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License