Integrating Blazor Components into Existing Asp.Net Core MVC Applications
Blazor offers many benefits to .Net developers ranging from providing a Single Page Application (SPA) framework option, to features like two-way binding and offline support just to name a few. But one of the main benefits that has been resonating with a lot of .Net developers is the fact that it’s component based. Whereas its highly recommended to start with a Blazor application whenever possible, it’s also plausible to consider integrating Blazor components into existing ASP.Net Core MVC applications(or Razor pages for that matter). The aforementioned scenario comes up in one of two cases:
- You have a huge investment in an existing ASP.Net Core MVC application and you are not ready to migrate to Blazor but would like to make use of Blazor components
- You would like to migrate to Blazor eventually but you are planning on gradually getting there
The solution is the same in both cases. It basically involves adding Blazor to your ASP.Net Core middleware. Now there are several posts out there that address this topic but most of them are either outdated or incomplete. Here is my attempt to provide a complete picture using the latest version of .Net Core (version 3.1 at the time of writing this post). The source code can be found here.
The first step towards this integration involves adding support for server side Blazor by adding it to your project’s dependency injection container. This is achieved by adding the Server Side Blazor service inside the Startup.cs file as shown below.
In the same startup.cs file go ahead and add an endpoint for the Blazor SignalR hub.
At this point you are almost ready to to add your Blazor component to your project. Blazor components must go into a Pages subfolder under the Components folder. This folder doesn’t exist under the MVC template . Go ahead and create that folder and sub-folder. Your project structure should now look like this: