加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – HttpClient不报告从Web API返回的异常

发布时间:2020-12-15 23:07:00 所属栏目:asp.Net 来源:网络整理
导读:我正在使用HttpClient来调用我的MVC 4 web api.在我的Web API调用中,它返回一个域对象.如果出现任何问题,将在服务器上抛出HttpResponseException,并显示自定义消息. [System.Web.Http.HttpGet] public Person Person(string loginName) { Person person = _p
我正在使用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”始终为“Not found”,对于500个代码,“Reason Server Error”为“Internal Server Error”.

有任何想法吗?如何从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);
    }
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读