.NET 8 Blazor Auto模式下WebAssembly调用Server的方法及教程咨询
.NET 8 Blazor Auto模式下WebAssembly调用Server的实现方案
一、解决Server项目无Controllers的问题
- 在Server项目中手动创建
Controllers文件夹,添加API控制器类,示例代码:
[ApiController] [Route("api/[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; [HttpGet] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }
- 在Server项目的
Program.cs中补充API服务配置:- 在
builder.Services.AddRazorComponents()之后添加:builder.Services.AddControllers(); - 在
app.MapRazorComponents<App>()之后添加:app.MapControllers();
- 在
二、配置HttpClient注入
在Client项目(命名通常为[项目名].Client)的Program.cs中注册HttpClient服务:
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
之后即可在Blazor组件中通过构造函数注入HttpClient:
private readonly HttpClient _http; public Weather(HttpClient http) { _http = http; }
三、实现WebAssembly对Server API的调用
在组件中替换硬编码数据,改为调用API获取数据,示例:
private List<WeatherForecast>? forecasts; protected override async Task OnInitializedAsync() { forecasts = await _http.GetFromJsonAsync<List<WeatherForecast>>("api/weatherforecast"); }
注:WeatherForecast实体类可直接在Client项目中定义;若需Server和Client共享,可手动创建Shared项目存放实体类,再让Server和Client项目引用该Shared项目。
四、推荐教程
- 微软官方文档:重点查看「Blazor Web应用中添加API控制器」和「从Blazor WebAssembly调用Web API」相关章节,覆盖Auto模式下的完整配置流程。
- .NET 8官方Blazor入门教程:跟着教程从零搭建包含API调用的Blazor Web项目,直观理解Auto模式的通信逻辑。
- 国内技术社区(博客园、掘金):搜索「.NET 8 Blazor Auto模式 API调用」,获取开发者实际项目中的配置细节和问题解决方案。
内容的提问来源于stack exchange,提问作者coolblue2000
相关产品推荐
相关产品推荐

