Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use blazor server-side inside a razor component library using areas?

I have an existing .net core 3.0 preview 7 web application. My application is mainly razor-pages organized into areas eg. Admin, Sales, etc. I am able to successfully use a blazor component if I put it at the root of the application, however, if I move the component to an RCL I can access the component but it is not responsive (clicking the button for the counter example does not increment the count).

I want to be able to go localhost/Admin/RazorPageContainingBlazorComponent or localhost/Sales/AnotherRazorPageContainingBlazorComponent

I get this error in chrome dev tools: ''' Error: Failed to complete negotiation with the server: Error

https://localhost:5000/myfeature/_blazor/negotiate 404 '''

I believe this is caused by the signalR hub being mapped to https://localhost:5000/, but I not sure how to add additional blazor hub mappings or how to change blazor.server.js to to use the root hub.

like image 249
ACertainDeveloper Avatar asked Aug 05 '19 21:08

ACertainDeveloper


People also ask

How do you reference a component in Blazor?

To capture a component reference in Blazor, use the @ref directive attribute. The value of the attribute should match the name of a settable field with the same type as the referenced component. When the parent component is rendered, the field is populated with the child component instance.

How does server-side Blazor work?

Server-side Blazor is executed on the server within an ASP.NET Core application. All UI updates, event handling, and JavaScript calls are handled from server by using a SignalR connection, even a button click will go to server.


2 Answers

After digging though both signalR documentation and the blazor.server.js file I was able to come up with a solution. Adding the code below to you're layout file configures the signalR hub to use an absolute path instead of a relative path.

<script src="~/_framework/blazor.server.js" autostart="false"></script>
<script>
    Blazor.start({
        configureSignalR: function (builder) {
            builder.withUrl("/_blazor");
        }
    });
</script>

This allows razor components to be used directly in a razor class library, using area routing.

like image 164
ACertainDeveloper Avatar answered Oct 11 '22 07:10

ACertainDeveloper


Hey we also found ourself with the same issue. A better solution would be to specify <base href="~/"/> in the head of the html and just referencing <script src="_framework/blazor.server.js"/>

so

<html>
<head>
<base href="~/"/>
</head>
<body>

<script src="_framework/blazor.server.js"/>
</body>
</html>
like image 29
Ivan Sander de Jong Avatar answered Oct 11 '22 08:10

Ivan Sander de Jong