0
votes

I'm planning to create an ASP.NET Core hosted Blazor WASM application but because of limited debugging experience and slower development, I'm choosing Blazor Server Application hosting a WebAPI instead to mimic the architecture of the said project type to ease switching back when .NET 5 is released. The problem is I don't know how to configure the Startup class to use WebAPI. Unfortunately, I can't find any links that demonstrate using a WebAPI in Blazor Server.

Assuming I already have my controllers added in the project, what should I modify in the ConfigureServices() and the Configure() methods of the Startup to use the controllers?

1
Can I ask if the WebAPI is for the Blazor app to use, or is it for use by something else? If it's only to provide data to Blazor you don't need it for Blazor server - the Blazor code already runs on the server. - Quango
@Quango It is to provide data for Blazor, but I thought that building the Server-Side app like a WASM-app will ease the switch to WASM so I won't have to change anything - DaaWaan
yes that's true. The best approach is encapsulate the data access in an interface, e.g. IDataAccess - for WASM create a WebAPI access code, for Server you can just fetch the data. If that makes sense. You can do WebAPI later when you need it. I have a demo app (bit out of date but the concept is the same: github.com/conficient/BlazorServicePattern - Quango
Nice! I was just thinking about it recently but I can't really find a reference for it. Thanks for the sample! - DaaWaan
@Quango By the way, I just realized that Controllers for WebAPIs (ControllerBase class since Controller is for MVC Views) return ActionResult<Model>. Have you ever had any experience with this case? - DaaWaan

1 Answers

2
votes

Anyway, finally figured it out. To use controllers in Blazor Server and in any ASP.NET Core application for an API, just map the controllers in the Configure().

public void Configure(IAppplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseEndpoints(endpoints => 
    {
        endpoints.MapControllers();
        ...
    });
}