有没有办法从 MVC 应用程序中的特定控制器操作为 Blazor 应用程序提供服务?

有没有办法从 MVC 应用程序中的特定控制器操作为 Blazor 应用程序提供服务?

问题描述:

我想在现有的 ASP.NET Core 3.0 MVC 项目中设置一个控制器操作来为 Blazor 应用提供服务.过去我看到过与其他 SPA 框架类似的东西,操作的视图只包含包含包的脚本标签,通常还有一些其他设置,例如将 SPA 构建放在 wwwroot 上以用于 MVC 项目.

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.

查看 Blazor 应用程序,它似乎在某种程度上类似,其中 index.html 文件包含 wasm 脚本.但老实说,我不确定从哪里开始设置它.有什么想法吗?

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?

似乎您正在使用 Blazor 客户端.基本上,Blazor 客户端应用程序的条目是加载blazor.webassembly.js>.这个脚本会动态下载所有的静态资源(*.wasm*.dlls).请注意,如果您可以使这些资产可用,即使没有 ASP.NET Core,您也可以托管 Blazor 客户端应用程序.

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.

由于您使用 ASP.NET Core MVC 作为服务器,一个简单的方法是:

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

  1. 添加对 Microsoft.AspNetCore.Blazor.Server 的包引用,以便我们可以为 *.wasm *.dll 文件提供只有一个代码.
  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" />

  • 添加对您的客户端项目的项目引用,以便我们可以从源代码生成静态数据.假设您的客户端 Web 程序集应用程序是 MyClientSideBlazorApp:

    <ProjectReference Include="..MyClientSideBlazorAppMyClientSideBlazorApp.csproj" />
    

  • 现在您可以在 Startup.cs 中注册一个中间件来提供静态文件:

  • And now you can register a middleware within the Startup.cs to serve the static files:

    app.UseClientSideBlazorFiles<MyClientSideBlazorApp.Startup>();
    app.UseStaticFiles();
    

  • 最后,在您想要为 blazor 提供服务的任何页面/视图中,例如 Home/Privacy.cshtml 视图文件,添加一个 加载条目以及 元素以确保相对路径正确.

  • 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.