Blazor WebAssembly调用ASP.NET Core Web API:GET正常POST无响应
问题:Blazor WebAssembly调用ASP.NET Core API的POST请求无响应,GET请求正常
我开发了一个用于Locations实体CRUD操作的ASP.NET Core Web API,Blazor WebAssembly客户端调用时,GET请求可正常获取数据库中的Locations数据并在页面网格展示,但POST请求无任何反应。Swagger测试POST请求能正常插入新Location,但客户端调用后无结果,新数据未写入数据库。
API端LocationController代码
using Microsoft.AspNetCore.Mvc; using BlazorAppDiscoveryAPI.Models; using Microsoft.Data.SqlClient; using Dapper; using System.Data; namespace BlazorAppDiscoveryAPI.Controllers { [ApiController] [Route("api/Locations")] public class LocationController : ControllerBase { static IConfiguration conf = (new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build()); public static string connectionString = conf["ConnectionStrings:Default"].ToString(); [HttpGet(Name = "GetLocations")] public IEnumerable<dynamic> Get() { string strSQL = "select * from dbo.Location"; using IDbConnection connection = new SqlConnection(connectionString); { return connection.Query(strSQL); } } [HttpPost] public int Add(LocationModel newLocation) { string strSQL = @"INSERT INTO dbo.Location(Location_NUM, Location_OWNER) VALUES(@Location_NUM, @Location_OWNER);"; using IDbConnection connection = new SqlConnection(connectionString); { return connection.Execute(strSQL, newLocation); } } } }
客户端Blazor组件代码
@code { private List<LocationModel> Locations; private LocationModel newLocation = new LocationModel(); protected override async Task OnInitializedAsync() { Locations = await LocationService.GetAllLocationsAsync(); } private async Task InsertLocation() { LocationModel s = new LocationModel { Location_NUM = newLocation.Location_NUM, Location_OWNER = newLocation.Location_OWNER }; await LocationService.InsertLocationAsync(s); newLocation = new LocationModel(); } }
客户端LocationService代码
using BlazorAppDiscovery.Client.Models; using System.Net.Http.Json; using Microsoft.Extensions.Configuration; namespace BlazorAppDiscovery.Client.Services { public class LocationService(HttpClient http) : ILocationService { public static string baseaddress = "https://localhost:7276/"; public async Task<List<LocationModel>> GetAllLocationsAsync() { string requestUri = baseaddress + "api/Locations/"; return await http.GetFromJsonAsync<List<LocationModel>>(requestUri); } public async Task InsertLocationAsync(LocationModel newLocation) { string requestUri = baseaddress + "api/Locations/"; await http.PostAsJsonAsync(requestUri, newLocation); } } }
可能的原因及解决方案
1. 跨域资源共享(CORS)配置缺失
GET属于简单请求可能被浏览器默认放行,但POST是非简单请求,需要服务器明确配置CORS规则:
在API项目的Program.cs中添加CORS中间件:
builder.Services.AddCors(options => { options.AddPolicy("AllowBlazorClient", policy => policy.WithOrigins("https://localhost:5001") // 替换为你的Blazor客户端地址 .AllowAnyHeader() .AllowAnyMethod()); }); // 注意中间件顺序:在UseRouting之后,UseAuthorization之前添加 app.UseCors("AllowBlazorClient");
2. HttpClient未处理响应错误
PostAsJsonAsync不会自动抛出HTTP错误状态码,需手动检查响应:
修改InsertLocationAsync方法:
public async Task InsertLocationAsync(LocationModel newLocation) { string requestUri = baseaddress + "api/Locations"; var response = await http.PostAsJsonAsync(requestUri, newLocation); // 触发错误状态码异常,便于调试 response.EnsureSuccessStatusCode(); }
同时在Blazor组件中添加异常捕获:
private async Task InsertLocation() { try { LocationModel s = new LocationModel { Location_NUM = newLocation.Location_NUM, Location_OWNER = newLocation.Location_OWNER }; await LocationService.InsertLocationAsync(s); // 插入成功后刷新列表 Locations = await LocationService.GetAllLocationsAsync(); newLocation = new LocationModel(); } catch (Exception ex) { Console.WriteLine($"插入失败:{ex.Message}"); } }
3. 模型绑定不匹配
确保客户端与API端的LocationModel属性名称、类型完全一致(JSON序列化默认区分大小写),比如Location_NUM、Location_OWNER的拼写和大小写必须完全相同。
4. 路由匹配不一致
API路由为api/Locations,客户端请求末尾多了斜杠api/Locations/,虽然ASP.NET Core通常兼容,但建议保持路由一致,修改客户端请求地址:
string requestUri = baseaddress + "api/Locations";
5. 静态配置初始化问题
API中静态构建IConfiguration的方式不规范,建议通过依赖注入获取配置:
修改LocationController:
private readonly string _connectionString; public LocationController(IConfiguration configuration) { _connectionString = configuration["ConnectionStrings:Default"]; }
内容的提问来源于stack exchange,提问作者John Marquez
相关产品推荐
相关产品推荐

