我在用着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 代码的“ReasonPhrase”始终为“内部服务器错误”。
有任何想法吗?如何从 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)