gpt4 book ai didi

c# - HttpClient不报告从Web API返回的异常

转载 作者:行者123 更新时间:2023-12-04 13:17:08 24 4
gpt4 key购买 nike

我正在使用HttpClient调用我的MVC 4 Web API。在我的Web API调用中,它返回一个域对象。如果出现任何问题,则会在服务器上抛出HttpResponseException并带有自定义消息。

 [System.Web.Http.HttpGet]
public Person Person(string loginName)
{
Person person = _profileRepository.GetPersonByEmail(loginName);
if (person == null)
throw new HttpResponseException(
Request.CreateResponse(HttpStatusCode.NotFound,
"Person not found by this id: " + id.ToString()));

return person;
}

我可以在使用IE F12的响应正文中看到自定义的错误消息。但是,当我使用 HttpClient调用它时,我没有得到自定义的错误消息,只有HTTP代码。对于404,“ReasonPhrase”始终为“未找到”,对于500个代码,始终为“内部服务器错误”。

有任何想法吗?我如何从Web API发回自定义错误消息,同时又将普通返回类型保留为我的域对象?

最佳答案

(将我的答案放在此处以获得更好的格式)

是的,我看到了,但是HttpResponseMessage没有body属性。我自己弄清楚了:response.Content.ReadAsStringAsync().Result;。示例代码:

public T GetService<T>( string requestUri)
{
HttpResponseMessage response = _client.GetAsync(requestUri).Result;
if( response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<T>().Result;
}
else
{
string msg = response.Content.ReadAsStringAsync().Result;
throw new Exception(msg);
}
}

关于c# - HttpClient不报告从Web API返回的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12103946/

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