1建立MVC项目(.net 6);
2 在项目启动文件Program.cs中添加Blazor框架;
var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddControllersWithViews();builder.Services.AddServerSideBlazor(); //Blazor相关服务var app = builder.Build();// Configure the HTTP request pipeline.if (!app.Environment.IsDevelopment()){app.UseExceptionHandler("/Home/Error");}app.UseStaticFiles();app.UseRouting();app.UseAuthorization();app.MapBlazorHub(); //映射Blazor路由app.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");app.Run();
3 新建_Imports.razor文件,内容如下:
@using .Http@using Microsoft.AspNetCore.Authorization@using ponents.Authorization@using ponents.Forms@using ponents.Routing@using ponents.Web@using ponents.Web.Virtualization@using Microsoft.JSInterop
4 在界面中引入blazor.js
<script src="_framework/blazor.server.js"></script>
5 在界面中引入组件
@using BlazorMVC.Views.Home //组件位置@{ViewData["Title"] = "Home Page";}<div class="text-center"><h1 class="display-4">Welcome</h1><component type="typeof(Test)" render-mode="ServerPrerendered" /> @*组件使用方式*@</div>