我有以下几种方法来收集汽车:
public async Task<IEnumerable<Car>> GetCars(object car, CancellationToken ct)
{
var uri = new Uri($"{_webApiUrl}Car/GetCars");
using (var httpClient = new HttpClient())
{
HttpContent content = new StringContent(JsonConvert.SerializeObject(car), Encoding.UTF8, "application/json");
var req = await httpClient.PostAsync(uri, content, ct);
var response = await req.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IEnumerable<Car>>(response);
}
}
在controller中的服务api中,我有以下内容:
[HttpPost]
[Route("api/[controller]/[action]")]
public IActionResult GetBottleTypeById(Car car)
{
return Ok(_carQuery.GetCars(car));
}
这两件事都很好--没有问题。
现在我需要保存
[HttpPost]
[Route("api/[controller]/[action]")]
public IActionResult UpdateOperation(Car car)
{
_carRepository.UpdateOperation(car) //UpdateOperation is void with try/catch - throw;
}
与
public async Task UpdateCar(Car selectedCar, CancellationToken ct)
{
var uri = new Uri($"{_webApiUrl}Car/UpdateOperation");
using (var httpClient = new HttpClient())
{
HttpContent content = new StringContent(JsonConvert.SerializeObject(selectedCar), Encoding.UTF8, "application/json");
var req = await httpClient.PostAsync(uri, content, ct);
var response = await req.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IEnumerable<Car>>(response);
}
}
我怎样才能把这两件事都准备好呢?
只需更改代码以返回
[HttpPost]
[Route("api/[controller]/[action]")]
public void UpdateOperation(Car car)
{
_carRepository.UpdateOperation(car) //UpdateOperation is void with try/catch - throw;
}
要使您的调用代码工作,您不需要从服务器接收任何东西,只需要接收HTTP响应消息。即使您的方法返回
请尝试以下操作:
public async Task UpdateCar(Car selectedCar, CancellationToken ct)
{
var uri = new Uri($"{_webApiUrl}Car/UpdateOperation");
using (var httpClient = new HttpClient())
{
HttpContent content = new StringContent(JsonConvert.SerializeObject(selectedCar), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(uri, content, ct);
if (response.IsSuccessStatusCode)
{
return;
}
else
{
// handle error
}
}
}