今天试了一下在Asp.net core Razor Pages/MVC程序中集成Blazor(Server-side),还是可以完美整合的,这里以Razor Pages为例(.net core 3.1),记录下相关过程。

1. 配置StartUp,添加Blazor服务

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
}

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/Index");
});

 2. 在根目录添加"_Imports.razor"

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop

这一步非常重要,如果没有_Imports.razor这个文件(注意需要放在根目录),则渲染方式和传统的Razor模板方式一样,不会和Blazor事件联动,例如,在本例中不会关联按钮事件。

 

 3.  添加组件Counter.razor

<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 32;
    private void IncrementCount()
    {
        currentCount++;
    }
}

 4. 在Index.cshtml中添加组件引用及blazor.server.js

<component type="typeof(Pages.Shared.Counter)" render-mode="ServerPrerendered" />
<script src="_framework/blazor.server.js"></script>

这里是用的component Tag Helper引用的组件,原始代码的方式是:

@(await Html.RenderComponentAsync<Pages.Shared.Counter>(RenderMode.ServerPrerendered))

5. 运行,即可看到二合一的效果了。
效果就不截图了。

posted on 2019-12-01 19:15  天方  阅读(1463)  评论(2编辑  收藏  举报