Blazor WebAssembly 调用 API 主要靠
IHttpClientFactory和
HttpClient,推荐用注入的客户端发请求,安全、可配置、支持拦截和生命周期管理。
使用 HttpClient 服务发起 GET 请求
在
Program.cs中已默认注册了命名客户端(如
"ServerAPI"),你只需在组件中注入并调用: 确保
Program.cs里有类似
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); 或更推荐的命名注册:builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));
组件中用 @inject IHttpClientFactory HttpClientFactory,然后
var client = HttpClientFactory.CreateClient("ServerAPI");
调用 await client.GetFromJsonAsync<t>("api/values")</t>,自动反序列化,简洁安全
POST 请求传参与处理响应
提交数据常用
PostAsJsonAsync,后端接收需匹配模型结构: 定义请求体类,比如
public class LoginRequest { public string Username { get; set; } }
组件中: var response = await client.PostAsJsonAsync("api/auth/login", new LoginRequest { Username = "user" });
检查 response.IsSuccessStatusCode,再用
await response.Content.ReadFromJsonAsync<loginresult>()</loginresult>解析结果 注意:WASM 运行在浏览器沙箱中,跨域需后端配 CORS,且不能绕过同源策略
错误处理与加载状态控制
真实场景中网络可能失败或延迟,别让 UI 卡住或静默出错:
用try/catch捕获
HttpRequestException,区分连接失败、404、500 等 配合
@if (isLoading) { <text>Loading...</text> } 显示加载态
对 401 响应可跳转登录页:if (response.StatusCode == HttpStatusCode.Unauthorized) Navigation.NavigateTo("/login");
避免在 OnInitializedAsync中直接 await 长耗时请求,建议用
Task.Run包裹或配合
StateHasChanged()手动刷新
自定义请求头与认证 Token
带身份凭证调用受保护接口很常见:
从本地存储读取 token:var token = await localStorage.GetItemAsStringAsync("auth_token");(需引用 Microsoft.AspNetCore.Components.Web.Extensions或用 JS Interop) 设置头:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
更优雅的做法是用 DelegatingHandler封装自动加 token 逻辑,注册时链入:
AddHttpClient(...).AddHttpMessageHandler<authhandler>();</authhandler>注意:WASM 无法访问 Cookie(浏览器限制),Token 必须显式传,通常存在 localStorage 或 sessionStorage
基本上就这些。核心是用好
IHttpClientFactory+ 异步方法 + 合理错误处理,不复杂但容易忽略加载态和跨域细节。
