HttpClient不报告从Web

HttpClient不报告从Web

本文介绍了HttpClient不报告从Web API返回的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HttpClient 调用我的MVC 4 Web API。在我的Web API调用中,它返回一个域对象。如果出现任何问题,将在服务器上抛出 HttpResponseException 并显示一条自定义消息。

I'm using HttpClient to call my MVC 4 web api. In my Web API call, it returns a domain object. If anything goes wrong, a HttpResponseException will be thrown at the server, with a customized message.

 [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个代码,始终为内部服务器错误。

I can see the customized error message in the response body using IE F12. However when I call it using HttpClient, I don't get the customized error message, only the http code. The "ReasonPhrase" is always "Not found" for 404, or "Internal Server Error" for 500 codes.

有什么想法吗?如何从Web API发回自定义错误消息,同时又将普通返回类型保留为我的域对象?

Any ideas? How do I send back the custom error message from the Web API, while keep the normal return type to be my domain object?

推荐答案

(在这里输入我的答案以获得更好的格式)

(Putting my answer here for better formatting)

是的,我看到了,但是HttpResponseMessage没有body属性。我自己弄清楚了: response.Content.ReadAsStringAsync()。Result; 。示例代码:

Yes I saw it but HttpResponseMessage doesn't have a body property. I figured it out myself: response.Content.ReadAsStringAsync().Result;. The sample code:

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);
    }
 }

这篇关于HttpClient不报告从Web API返回的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:11