I figured out how to get it running. I am using .NET 5.0.
First create a new Solution with a Razor Class Library project (Check the checkbox Support pages and views
).
And create a MVC project.
In Startups.cs
add the following:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddRazorPages();
services.AddServerSideBlazor();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Also make sure you have app.UseStaticFiles();
in your Configure
method.
Then, in your Razor Class Library, you can copy and paste the Pages, Shared folders and all other razor files from the example Blazor webassembly project. Also don't forget the wwwroot css folder and add your own wwwroot folder to your RCL.
In the Pages folder also create a new cshtml
file. This will be the entry point to your Blazor app.
Example code:
@page
@using PROJECTNAME
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Blazor WebAssembly Prerendered</title>
<base href="~/" />
<link href="/_content/PROJECTID/css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="/_content/PROJECTID/css/app.css" rel="stylesheet" />
@*https://docs.microsoft.com/de-de/aspnet/core/blazor/components/css-isolation?view=aspnetcore-5.0#razor-class-library-rcl-support*@
<link href="/_content/PROJECTID/PROJECTNAME.bundle.scp.css" rel="stylesheet" />
</head>
<body>
<app>
<component type="typeof(App)" render-mode="ServerPrerendered" />
</app>
</body>
</html>
<script src="_framework/blazor.server.js"></script> <!--blazor.webassembly.js didn't work-->
The important parts are the <base href="~/" />
and the _framework/blazor.server.js
.
If you don't map this page to be at the root, like @page "/"
you have to make sure all the static content is mapped to the project-id correctly.
Also make sure the paths in the example projects NavMenu.razor
are correct if you don't use / as the root. Has to be correct in the Razor Components too.
If you have problems with the _Imports.razor
file, try adding the NuGet package Microsoft.AspNetCore.Components.WebAssembly
Also add the correct namespace for your shared folder, in the example project it's PROJECTNAME.Shared
. Change it accordingly.
Here's a blogpost that helped me get things the right way: https://blog.joelving.dk/2020/02/reusable-ui-and-interchangable-hosting-models-in-blazor/