[Fixed] JsonSerializer throws exception in Blazor Web App .NET 8, when AOT is enabled – .net

by
Maya Patel
.net-4.8 .net-8.0 blazor

Quick Fix: For Blazor Web App .NET 8, enable Ahead-of-Time (AOT) compilation only for the ".Client" project, not the main project. This should resolve the exception thrown by JsonSerializer when AOT is enabled.

The Problem:

In a Blazor WebAssembly App targeting .NET 8 with Ahead-of-Time (AOT) compilation, calling System.Text.Json.JsonSerializer.Serialize() throws an InvalidOperationException. Enabling AOT brings a performance boost to Blazor WebAssembly apps but introduces this issue when serializing JSON data.

The Solutions:

Solution 1: Configure AOT for the .Client project, not the main project

Solution:

Enable Ahead-of-Time (AOT) compilation for the .Client project, but leave the main project with AOT disabled.

  1. Open the project properties for the .Client project:
    – In Visual Studio, right-click the .Client project and select Properties.
    – In the Properties window, navigate to the Build tab.
  2. Enable AOT compilation for the .Client project:
    – In the Build tab, find the Enable Ahead-of-Time (AOT) compilation checkbox.
    – Check the checkbox to enable AOT compilation.
  3. Run the project:
    – Build and run the project. The .Client project will now be compiled with AOT, while the main project will not.

Explanation:

The error message indicates that reflection-based serialization has been disabled for the application. This restriction is introduced to improve performance and security when AOT compilation is enabled. However, it can cause issues with certain operations that rely on reflection, such as serializing and deserializing objects using JsonSerializer.

By enabling AOT compilation for the .Client project and leaving it disabled for the main project, you can take advantage of the performance benefits of AOT compilation while avoiding the reflection-based serialization issue. This approach allows you to use JsonSerializer in the client-side code (.Client project) without encountering the error.

Solution 2: Native AoT is not supported for Blazor.

Native AoT is not compatible with Blazor. This is because Blazor relies on reflection, which is not supported in native AoT. The announcement blog post states:

The following table summarizes ASP.NET Core feature compatibility with native AOT:

                  

Blazor ❌Not supported

This means that Blazor cannot be used with native AoT in either Blazor WebAssembly or Blazor Server-side.

Q&A

Why am I getting an exception when using JsonSerializer in my Blazor Web App with AOT enabled?

Native AOT is not supported for Blazor. Enable AOT for the .Client project, not the normal project.

What is the difference between AOT and native AOT?

Native AOT is not supported for Blazor. There may be a difference between the two, but it is not documented.