gpt4 book ai didi

c# - 为什么详细的错误信息没有传递给 HttpClient?

转载 作者:行者123 更新时间:2023-12-04 11:19:05 26 4
gpt4 key购买 nike

我使用的是自动生成的默认 Web Api Controller 。我正在客户端测试验证和错误处理。但不知何故,我意识到详细错误消息没有传递给客户端。如果我在这两种情况下都抛出 HttpResponseException 或返回 IHttpActionResult,客户端只会看到“错误请求”而不是详细消息。谁能解释一下出了什么问题?

     public IHttpActionResult Delete(int id)
{
if (id <= 0)
{
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("Id should be greater than zero.", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound

};
throw new HttpResponseException(response) // Either this way
}

var itemToDelete = (from i in Values
where i.Id == id
select i).SingleOrDefault();

if (itemToDelete == null)
{
return BadRequest(string.Format("Unable to find a value for the Id {0}", id)); // Or This way
}

Values.Remove(itemToDelete);
return Ok();
}

客户端代码为:
 private async static Task DeleteValue(int id)
{

var url = "http://localhost:13628/api/Values/" + id;
using (var client = new HttpClient())
{
var response = await client.DeleteAsync(url);
if (response.IsSuccessStatusCode)
{
await ReadValues();
}
else
{
Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(response.StatusCode);
}
}
}

以上都不行??

谢谢

最佳答案

在您的客户端更改 Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
它会给出详细的错误信息。

关于c# - 为什么详细的错误信息没有传递给 HttpClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40216052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com