Is there a way to serve a Blazor app from a specific controller action in a MVC app?

倾然丶 夕夏残阳落幕 提交于 2021-02-08 05:13:40

问题


I'd like to set up a controller action in a already existing ASP.NET Core 3.0 MVC project to serve a Blazor app. I've seen something similar with other SPA frameworks in the past, the View for the action just includes contains the script tag with the bundle, there's usually some other setup like having the SPA build placed on wwwroot for the MVC project.

Looking at the Blazor app it seems similar to some extent, where the index.html file includes the wasm script. But I'm honestly not sure where to start to set it up. Any ideas?


回答1:


Seems you're using Blazor Client Side. Basically, the entry for Blazor Client Side App is the <script> that loads the blazor.webassembly.js. And this script will download all the static assets( *.wasm and *.dlls) dynamically. Note that if you can make these assets available, you can host the Blazor Client Side App even without ASP.NET Core.

Since you're using ASP.NET Core MVC as the server, an easy approach would be :

  1. Add a package reference to Microsoft.AspNetCore.Blazor.Server so that we can serve the *.wasm *.dll files with just one code.
    <PackageReference Include="Microsoft.AspNetCore.Blazor.Server" Version="3.0.0-preview9.19465.2" />
    
  2. Add a project reference to your ClientSide Project so that we can generate the statics from source code. Let's say your client side web assembly app is MyClientSideBlazorApp:

    <ProjectReference Include="..\MyClientSideBlazorApp\MyClientSideBlazorApp.csproj" />
    
  3. And now you can register a middleware within the Startup.cs to serve the static files:

    app.UseClientSideBlazorFiles<MyClientSideBlazorApp.Startup>();
    app.UseStaticFiles();
    
  4. Finally, within any page/view that you want to serve the blazor, for example, the Home/Privacy.cshtml view file, add a <script> to load the entry and also a <base> element to make sure the relative path is correct.

    @{
       Layout = null;
    }
    <base href="/">
    
    ... 
    
    <app>Loading...</app>
    
    <script src="/_framework/blazor.webassembly.js"></script>
    

It should work fine now.



来源:https://stackoverflow.com/questions/58479724/is-there-a-way-to-serve-a-blazor-app-from-a-specific-controller-action-in-a-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!