我似乎不太明白如何从我的用ASP.NET托管的Blazor WASM项目中调用HTTPPOST函数。我很难找到任何使用.NET 6之后的POST方法的例子,可能是因为它太新了。我尝试过将内容头设置为JSON,并尝试过从实际的控制器函数中检索请求体的许多不同方法,但我只得到500、415和400个错误。我也尝试过不使用绑定控制器函数的模型,但没有用。不过,我不认为这是问题所在,因为据我所知,使用[ApiController]属性可以推断出正确的模型绑定。我只能想象这个问题源于HTTP调用。
调用方法的服务:
public async Task CreateUser(User user)
{
await _httpClient.PostAsJsonAsync("users", user);
}
控制器功能:
[HttpPost]
public async Task PostUser(User user)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
}
上面代码中给出的只是一个简单的400错误。
此外,我已经手动将一个测试用户添加到数据库中,并且我能够毫无问题地检索它。
下面是我的一个演示项目中的一些代码,显示了获取WeatherForecast记录的API调用。
以下是Web程序集项目DataBroker:
public class WeatherForecastAPIDataBroker : IWeatherForecastDataBroker
{
private readonly HttpClient? httpClient;
public WeatherForecastAPIDataBroker(HttpClient httpClient)
=> this.httpClient = httpClient!;
public async ValueTask<bool> AddForecastAsync(WeatherForecast record)
{
var response = await this.httpClient!.PostAsJsonAsync<WeatherForecast>($"/api/weatherforecast/add", record);
var result = await response.Content.ReadFromJsonAsync<bool>();
return result;
}
public async ValueTask<bool> DeleteForecastAsync(Guid Id)
{
var response = await this.httpClient!.PostAsJsonAsync<Guid>($"/api/weatherforecast/delete", Id);
var result = await response.Content.ReadFromJsonAsync<bool>();
return result;
}
public async ValueTask<List<WeatherForecast>> GetWeatherForecastsAsync()
{
var list = await this.httpClient!.GetFromJsonAsync<List<WeatherForecast>>($"/api/weatherforecast/list");
return list!;
}
}
这是它调用的控制器:
namespace Blazr.Demo.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private IWeatherForecastDataBroker weatherForecastDataBroker;
public WeatherForecastController(IWeatherForecastDataBroker weatherForecastDataBroker)
=> this.weatherForecastDataBroker = weatherForecastDataBroker;
[Route("/api/weatherforecast/list")]
[HttpGet]
public async Task<List<WeatherForecast>> GetForecastAsync()
=> await weatherForecastDataBroker.GetWeatherForecastsAsync();
[Route("/api/weatherforecast/add")]
[HttpPost]
public async Task<bool> AddRecordAsync([FromBody] WeatherForecast record)
=> await weatherForecastDataBroker.AddForecastAsync(record);
[Route("/api/weatherforecast/delete")]
[HttpPost]
public async Task<bool> DeleteRecordAsync([FromBody] Guid Id)
=> await weatherForecastDataBroker.DeleteForecastAsync(Id);
}
演示项目Blazor.Demo 的回购
控制器代码数据代理代码