将服务器端Blazor添加到现有的MVC Core应用程序 [英] Adding Server-Side Blazor to an existing MVC Core app

查看:115
本文介绍了将服务器端Blazor添加到现有的MVC Core应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完全可运行的Blazor服务器端项目和一个.NET Core 3 MVC项目,它们都在同一解决方案中.我现在正在尝试在我的MVC项目中使用Blazor项目中的组件.

I have a fully operative Blazor server-side project and a .NET Core 3 MVC project, both in the same solution. I'm now trying to use the components from the Blazor project in my MVC project.

我设法将组件呈现在MVC页面上,但是在Blazor组件上单击按钮不会触发组件的onclick事件,相反,我只是导航到

I've managed to get the components to render on an MVC page, but button clicks on the Blazor component don't trigger the onclick events for the components, instead I just get navigated to https://localhost:44341/?

我不清楚我需要在MVC解决方案中进行哪些更改才能使其正常工作?官方文档谈及在MVC项目中使用组件,并在,但都没有详细介绍如何实现.

I'm unclear as to exactly what changes I need to make in the MVC solution to get this working? The official documentation talks about using components in and MVC project and it's mentioned in this video chat with Dan Roth, but neither go into the detail of how to achieve it.

有人可以引导我完成如何将服务器端Blazor改造为MVC项目的完整步骤(或为我提供示例)吗?

Could anyone walk me though the full steps on how to retrofit server-side Blazor into an MVC project (or point me at an example)?

我的Blazor项目仍然具有标准模板的Counter组件,因此我尝试通过引用Blazor项目并将其添加到我的MVC解决方案中,然后将其添加到我的index.cshtml文件中:

My Blazor project still has the standard template's Counter component, so I've tried to add that to my MVC solution by referencing the Blazor project and then adding this to my index.cshtml file:

<div id="Counter">
  @(await Html.RenderComponentAsync<Counter>())
</div>

可以正确渲染,但是按钮的单击不起作用.

That renders correctly but the button clicks don't work.

我已将JS文件添加到MVC应用程序的_Layout页面:

I've added the JS file to MVC apps _Layout page:

<script src="_framework/blazor.server.js"></script>

在MVC项目的Startup.cs文件中打开服务器端Blazor:

Turned on Server Side Blazor in the MVC project's Startup.cs file:

services.AddServerSideBlazor();

我还向MVC项目中添加了Pages和Shared目录,并复制了_Imports和MainLayout文件-不确定是否需要.

I've also added Pages and Shared directories to the MVC project and copied over the _Imports and MainLayout files - not sure if that's needed.

如果那没做,我尝试从所有Blazor模板(客户端,客户端托管和服务器端)中分解新项目以寻找线索,但是所有这些示例均设置为具有以下功能的完整SPA .html文件中托管有一个Blazor入口点(App文件),而我想在许多不同的现有MVC页面上呈现Blazor组件.

When that didn't do it, I tried spinning up new projects from all the Blazor templates (client, client-hosted and server-side) to look for clues, but all of those examples are set up as complete SPAs with a single Blazor entry point (the App file) hosted in a .html file, whereas I want to render Blazor components on lots of different existing MVC pages.

然后,我尝试将那些项目的一部分(以及我的Blazor项目的一部分)添加到MVC项目中,但无法使其完全正常工作.

I then experimented with adding parts of those projects (and parts of my working Blazor project) into the MVC project, but can't get it to work fully.

我也尝试遵循此处的答案,但这是将Blazor组件文件添加到MVC项目中的工作,而我的Blazor文件当前(大部分)位于其他项目中.

I tried following the answer here too, but that's working with adding the Blazor component files into the MVC project, whereas my Blazor files are currently (mostly) in a different project.

  • 我已经在MVC应用程序的Startup.cs中添加了services.AddServerSideBlazor();.那里还有其他需要吗?
  • 我的MVC应用仍在传统的AspNetCore.Routing上,如果仅将组件放在现有的MVC页面上(我将没有Blazor页面,而只有Blazor组件),我是否仍需要切换到Core 3的端点路由? ).
  • 在浏览器中运行的blazor javascript文件与(通过SignalR)对话的Blazor的服务器端部分是否需要端点路由?我从js文件的浏览器中收到404.
  • 如果我只是托管组件,我是否仍需要"App"(App.razor)类/页面作为入口点?
  • 如果是这样,我是否需要将_Host.cshtml中的<app>@(await Html.RenderComponentAsync<App>())</app>行放在我的MVC项目中的某个地方?
  • 我是否需要从MVC项目中的Blazor项目中复制Pages和Shared文件夹,以及两个_Imports.razor文件和MainLayout.razor文件?
  • 我认为Blazor现在是Microsoft.NETCore.Platforms文件的一部分(在MVC项目的SDK节点下引用),所以我认为我不需要为Blazor向MVC添加单独的NuGet软件包.项目?
  • I've added services.AddServerSideBlazor(); in the MVC app's Startup.cs. is anything else needed there?
  • My MVC app is still on traditional AspNetCore.Routing, do I still need to switch to Core 3's endpoint routing if I'm only placing the components on existing MVC pages (I.e. I won't have Blazor pages, just Blazor components).
  • Does the server-side part of Blazor that the blazor javascript file running in the browser talks to (via SignalR) need endpoint routing? I'm getting a 404 in the browser from the js file.
  • Do I still need the `App' (App.razor) class/page as an entry point if I'm just hosting components?
  • If so, do I need to put the <app>@(await Html.RenderComponentAsync<App>())</app> line from _Host.cshtml somewhere in my MVC project?
  • Do I need to reproduce the Pages and Shared folders from the Blazor project in my MVC project, and also the two _Imports.razor files and the MainLayout.razor file?
  • I think Blazor is now part of the Microsoft.NETCore.Platforms file (referenced under the SDK node in the MVC project), so am I right to think I don't need to add separate NuGet packages for Blazor to the MVC project?

推荐答案

我现在已经深入到此.在我的问题中描述了所有试验和错误之后,该解决方案竟然只涉及很少的代码.

I've got to the bottom of this now. After all the trial and error described in my question the solution turns out to involve surprisingly little code.

下面的答案假定您的解决方案中有一个服务器端Blazor项目,并且在同一解决方案的单独MVC项目中尝试使用该项目中的组件.我是在VS2019中使用Core 3 Preview 5做到的.

The answer below assumes you have a working server-side Blazor project in your solution and are trying to use components from that project in a separate MVC project in that same solution. I did this in VS2019, using Core 3 Preview 5.

请参见页面底部,或指向同一项目中的MVC和Blazor示例的链接.

See the bottom of the page or a link to an example of MVC and Blazor in the same project.

您只需要添加对blazor项目的引用:

You just need to add a reference to your blazor project:

    <ProjectReference Include="..\MyClient.Web.Blazor\MyClient.Web.Blazor.csproj" />

更改为MVC项目的Views \ Shared \ _Layout.cshtml文件

将基本网址添加到头部:

Changes to the MVC project's Views\Shared\_Layout.cshtml file

Add the base url into the head:

<head>
<meta charset="utf-8" />
<base href="~/" />

添加对Blazor JS脚本的引用

Add a reference to the Blazor JS Script

<script src="_framework/blazor.server.js"></script>

(这在您的本地文件系统上实际上并不存在,Blazor会在应用程序到达浏览器时自动对其进行排序)

(This doesn't actually exist on your local file system, Blazor automagically sorts it out by the time the app gets to the browser)

这是完成实际工作的地方

This is where the real work is done

ConfigureServices方法中添加:

services.AddServerSideBlazor();

然后我将配置切换到新样式的Core 3配置(因此不再使用AddMvc方法):

I then switched my configuration over to the new style Core 3 configuration (so no longer using the AddMvc method):

services.AddControllersWithViews()            
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    });

services.AddRazorPages();

然后最终让我全部使用的更改是通过Configure(IApplicationBuilder app, IWebHostEnvironment env)方法切换到Core 3的端点路由:

And then the change that finally got it all working for me was to switch to Core 3's endpoint routing in the Configure(IApplicationBuilder app, IWebHostEnvironment env) method:


app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
    endpoints.MapBlazorHub();
});

//app.UseMvc(routes =>
//{
//    routes.MapRoute(
//        name: "MyArea",
//        template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

//    routes.MapRoute(
//        name: "default",
//        template: "{controller=Home}/{action=Index}/{id?}");
//});

注释掉的代码显示了我正在使用的旧样式路由.我认为是endpoints.MapBlazorHub();的缺失导致了我的按钮点击问题

The commented out code shows the old style routing I was using. I think it was the absence of endpoints.MapBlazorHub(); that was causing my button click issue

Blazor项目不需要任何更改即可开始工作.

No changes were needed to the Blazor project to get this working.

完成上述所有操作后,要使您的组件在MVC页面上呈现,所需要做的就是添加

Once you've done all of the above, all that's needed to get your component to render on an MVC page is to add

 @(await Html.RenderComponentAsync<YourComponent>())

这应该在MVC页面和Razor页面上都可以使用.

That should work on both an MVC page and a Razor page.

上述更改是我进行工作所需要做的全部工作. Core 5有一个已知问题,一旦您导航到带有Blazor组件的MVC或Razor页面,在刷新页面之前,路由将不再起作用-URL将在浏览器的地址栏中更改,但不会进行导航.

The above changes were all that I needed to make to get it working. There is a known issue with Core 5 where once you navigate to an MVC or Razor page with a Blazor component on it, the routing will no longer work until the page is refreshed - the URLs will change in the browser's address bar, but no navigation will occur.

我现在正在预览6上运行,并且可以确认从预览6开始已经解决了路由问题.

I'm now running on Preview 6 and I can confirm the routing issue is now fixed from Preview 6 onward.

Chris Sainty在以下示例中将服务器端Blazor组件添加到现有MVC 项目中的示例:

Chris Sainty has an example of server-side Blazor components added in to an existing MVC project here: Using Blazor Components In An Existing MVC Application (source here)

这篇关于将服务器端Blazor添加到现有的MVC Core应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆