Cal*_*vin 6 asp.net-web-api dotnet-httpclient
我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用IE F12在响应正文中看到自定义的错误消息.但是,当我使用它时HttpClient,我没有得到自定义的错误消息,只有http代码.对于404,"ReasonPhrase"始终为"Not found",对于500个代码,"Reason Server Error"为"Internal Server Error".
有任何想法吗?如何从Web API发回自定义错误消息,同时保持正常的返回类型为我的域对象?
Cal*_*vin 14
(把我的答案放在这里以便更好地格式化)
是的我看到了它,但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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8302 次 |
| 最近记录: |