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

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)

  • 您应该警惕直接从`ReadAsAsync <T>`调用`Result`,因为这会导致间歇性的线程问题.相反,尝试:`var contentTask = response.Content.ReadAsAsync <T>();`后跟`contentTask.Wait();`然后`return contentTask.Result;` (5认同)
  • @Sixto:你能描述一下线程问题吗?[Result](http://msdn.microsoft.com/en-us/library/vstudio/dd321468(v = vs.110).aspx)文档说"此属性的get访问器确保异步操作完成回来之前." 听起来好像是对"等待"的调用. (3认同)