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

标签 c# 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;
    }

我可以在使用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/

相关文章:

c# - 使用 Destroy() 函数时出现缺少引用异常

c# - Cosmos db OFFSET LIMIT 子句不起作用

c# - Asp.Net 核心 "remember me"持久性 cookie 在部署后不起作用

c# - 大数据量的 Web API 中的 502 错误

c# - 找到与请求 (GET) 匹配的多个操作

c# - 我需要将 2 列的数据合并到另一列。然后将该添加列的所有行合并到另一个表中的一个单元格中

c# - 有没有办法在redis缓存中制作类似文件夹的层次结构?

c# - 为什么我不能使用HttpClient 登录这个ASP.NET 网站?

servicestack - HttpClient 将 HTTP GET 请求流水线化到 ServiceStack API

c# - HttpClient AutomaticDecompression 使用 gzip,而不是 deflate