我需要做什么才能将控制器添加到 .NET 8 Blazor Wasm 应用程序?该模板现在创建计数器和天气,硬编码在 Razor 页面中,根本没有用。
用于添加控制器的模板。如何恢复此功能?
我尝试通过添加
builder.Services.AddHttpClient()
、UseControllers()
等来设置它,但在尝试调用控制器端点时我只是得到 404。
这是我的服务器项目
program.cs
:
using RWeb.Client.Pages;
using RWeb.Components;
using RWeb.Controllers;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveWebAssemblyComponents();
builder.Services.AddControllersWithViews(); // Add this line
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting(); // Add this line
app.UseAntiforgery();
app.UseAuthorization(); // Add this line
app.MapRazorComponents<App>()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(RecoWeb.Client._Imports).Assembly);
app.MapControllers();
app.Run();
这是客户项目的
program.cs
:
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));
await builder.Build().RunAsync();
需要明确的是,这是一个带有客户端和服务器项目的 WASM 托管应用程序。
这个博客看到描述。作为替代选项,我们现在有 blazor Web 应用程序。
以我的拙见,您现在正在尝试在.Net 8 中托管 Blazor Web Assembly + asp.net core。所以我认为现在有 2 个选项作为替代。一种是我们使用 blazor web assembly 独立应用程序,然后在同一解决方案中创建另一个 Web api 项目来为其提供服务。只需要在web api项目中添加CORS策略即可。另一个选择是使用 blazor web 应用程序,为了继续从 web assembly 中获得好处,您可以选择渲染模式为 Interactive Auto。 那么你不需要Controller,只需将Service注入到你的组件中即可。