Blazor Server + WebAPI = FTW

Mark E. Davis
3 min readDec 17, 2019

--

We are working on a mobile app that needs a web API back-end for the data as well as a simple user management web app. We’d love to a single Web Service that can serve both the JSON data for the mobile app via REST API and the Blazor web app for the the users. It’s surprisingly straightforward.

TL;DR: Just check the repo or more specifically, check the commit of merit.

Use the context menu to load up the scaffolding templates

Start by creating a new Blazor Server App and create an “Api” folder just for fun.

Next we’ll be adding a WebAPI Controller, and the easiest way to do that is with the context menu: Add :: New Scaffolding Item…

Pick the API Controller template with actions
Give it a name like TestController

So far, so normal. Adding some MVC code (WebAPI is really MVC) to Blazor doesn’t really do anything and if you atop at this point the Blazor routing will just 404 on any api/api. But it’s all ASP.Net so your tweaks are readily at hand.

According to a bug report I found, we make a few edits to Startup.cs and we’ll be up and running in no time.

Add Mvc, and disable default Razor pages endpoint routing.

Endpoint routing is the default routing style for Razor Pages and thus Blazor as well. Blazor components are Razor components after all. Because we are overloading the routing by adding MVC to the mix, we need to disable endpoint routing. There are some great error messages that will help make this discoverable if you get lost.

really useful error message if you get lost
Add MVC routing in the startup config.

Now we are using MVC Routing as well as regular routing. So you can fire up the Blazor app and all the navigation works.

But, you can also change the URL to hit the WebAPI controller and it just works too!

So now we get to have a single Web Service, share the data models and data access between the Blazor all and the Modile app and revel in the simplicity.

--

--