blazor logo

Overview

Walk through taking an existing asp.net mvc app and adding server side blazor support.

Pre-requisits

  • an existing asp.net mvc app running .net 5

New files

_Imports.razor

default using statements for blazor components

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop

App.razor

blazor routing

<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" />
</Found>
</Router>

Pages/Counter.razor

blazor component

@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}

Changed files

startup.cs

add blazor server side (no default blazor routing as routing handled by mvc)

public void ConfigureServices(IServiceCollection services)
{
services.AddServerSideBlazor(); // ADD
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapBlazorHub(); // ADD
});
}

Index.cshtml

add blazor component to existing mvc view

@using asp_net_mvc.Pages // ADD
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<component type="typeof(Counter)" render-mode="Server" /> // ADD
<script src="_framework/blazor.server.js"></script> // ADD

Notes

  • this post demonstrates adding a blazor component to an existing mvc view page
  • original mvc code base is mvc visual studio template
  • additional code comes from blazor server side visual studio template
  • this is not client side blazor aka wasm
  • watch out for casing; blazor components must start capitalized

Code links

References