Reputation: 131
I have an existing .net core 3.1 MVC application that I've started adding Blazor components to. This is working great, the components render and work as expected. Currently to get to a page that uses Blazor I am adding a controller action and view which handles the routing then I add the component tag to the view to render the Blazor component.
So let's say I have a Customers Blazor component, which is really a customers "page", I do the following.
<component type="typeof(MyApp.Pages.Customers)" render-mode="Server" />
Like I said, all of this works just fine it's just a lot of overhead for every page I add that uses Blazor. It would be nice to be able to just use the built-in Blazor routing for pages. If this worked I could just add the Customers Blazor component in the Pages folder and add the @page tag like this:
@page "/Customers"
Unfortunately this does not work, I get a 404 if I try to use this method.
I have followed the instructions in this article but still receive a 404: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/integrate-components?view=aspnetcore-3.1#use-routable-components-in-an-mvc-app
Has anyone got this working? Is it even possible?
Thanks!
Upvotes: 5
Views: 2450
Reputation: 3402
Start to finish with a fresh dotnet new mvc
application, this is how you can do this in .NET 5.0
...
Inside of ConfigureServices
, add:
services.AddRazorPages();
services.AddServerSideBlazor();
Inside of Configure
underneath UseEndpoints
, add:
endpoints.MapFallbackToPage("/_Host");
endpoints.MapBlazorHub()
Inside of your main layout, add the blazor server js
<script src="_framework/blazor.server.js"></script>
Using an _Imports.razor
file, reference: Microsoft.AspNetCore.Components.Web
Add a _Host.cshtml
file (pull it from a Blazor app)
// _Host.cshtml
@page "/blazor"
@namespace BlazorTechTalk.MvcWithBlazorUI.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<component type="typeof(App)" render-mode="ServerPrerendered" />
Add an App.razor
component (from a Blazor app)
Add an MainLayout
component (from a Blazor app)
@inherits LayoutComponentBase
@Body
Phew, you're done, you can now add BlazorPage.razor
pages and components inside your MVC project!
@page "/blazorpage"
<h3>BlazorPage</h3>
Just in case anyone stumbles upon this and only needs Blazor components
Do step 1-4 but you can omit:
services.AddRazorPages();
endpoints.MapToFallbackFile("/Host");
Upvotes: 9