提问者:小点点

将控制器和http请求准备为不返回值的preocess请求


我有以下几种方法来收集汽车:

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));
}

这两件事都很好--没有问题。

现在我需要保存,并且不需要返回什么(最终我可以返回true或false,不管它是否成功)。问题是我不确定应该是什么样子,如果我这样做,它会显示:

[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);
       }
}

我怎样才能把这两件事都准备好呢?


共1个答案

匿名用户

只需更改代码以返回。ASP.NET足够聪明,只要没有从void方法中抛出异常,就可以发送

[HttpPost]
[Route("api/[controller]/[action]")]
public void UpdateOperation(Car car)
{
      _carRepository.UpdateOperation(car) //UpdateOperation is void with try/catch - throw;
}

要使您的调用代码工作,您不需要从服务器接收任何东西,只需要接收HTTP响应消息。即使您的方法返回,HTTP服务器仍然发送一个状态码(200,500等)和一些头供您检查。

请尝试以下操作:

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
           }
       }
}