Blazor: How to fix System.NullReferenceException in _Host.cshtml file

Fixing Blazor NullException in _host.cshtml file

I'm currently experimenting with Blazor, a Microsoft Web Framework, and the other day I encountered a strange error that took me a while to figure out how to fix. When running the Blazor Server App, I received the System.NullReferenceException: 'Object reference not set to an instance of an object.' exception error in Visual Studio inside the generated _Host.cshtml file.

The error didn't even show in the browser, it happened still in Visual Studio at Pages/_Host.cshtml at the following line:

<component type="typeof(App)" render-mode="ServerPrerendered" />

Visual Studio IDE - getting System.NullReferenceException exception in Blazor Server App inside the _Host.cshtml file

Click image to enlarge

Examining the exception in greater detail revealed that it happened at Pages__Host.ExecuteAsync() method, but this didn't help me locate the cause of the error.

Cause of the issue - duplicate route

It turned out that the day before when I was adding a new template, I made a duplicate of the existing razor template and forgot to change the @page directive, which defines the route or URL path to the component.

The @page directive can be found at the top of the razor templates. For example, the first few lines of the default generated Counter.razor template are as follows:

@page "/counter"

<PageTitle>Counter</PageTitle>
...

So, If you are also getting the same Null Exception error in Pages/_Host.cshtml, double-check to make sure that each @page directive is unique.

Other causes

Additionally, there are other causes for this error. If you don't have any duplicate @page directives, take a look at this StackOverflow page for possible causes and solutions.

Summary

When working with Blazor, you might encounter the "System.NullReferenceException: 'Object reference not set to an instance of an object" error in _Host.cshtml. The error doesn't even appear in the browser but is shown in Visual Studio IDE. There might be several reasons for this error, but in my case, it was simply due to two razor templates having the same @page directive at the top of the template.

Tags:

Write a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.