6

HttpClientMVC 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 コードのみが表示されます。「ReasonPhrase」は、404 の場合は常に「見つかりません」、500 コードの場合は「Internal Server Error」です。

何か案は?通常の戻り値の型をドメイン オブジェクトのままにして、Web API からカスタム エラー メッセージを返すにはどうすればよいですか?

4

3 に答える 3

15

(より良いフォーマットのためにここに私の答えを入れてください)

はい、見ましたが、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);
    }
 }
于 2012-08-24T16:17:04.790 に答える
2

応答から例外を取得する際のロジックの一部を抜き出しました。

これにより、例外、内部例外、内部例外の抽出が非常に簡単になります:)など

public static class HttpResponseMessageExtension
{
    public static async Task<ExceptionResponse> ExceptionResponse(this HttpResponseMessage httpResponseMessage)
    {
        string responseContent = await httpResponseMessage.Content.ReadAsStringAsync();
        ExceptionResponse exceptionResponse = JsonConvert.DeserializeObject<ExceptionResponse>(responseContent);
        return exceptionResponse;
    }
}

public class ExceptionResponse
{
    public string Message { get; set; }
    public string ExceptionMessage { get; set; }
    public string ExceptionType { get; set; }
    public string StackTrace { get; set; }
    public ExceptionResponse InnerException { get; set; }
}

詳細については、このブログ投稿を参照してください。

于 2016-08-04T23:41:50.527 に答える
0

カスタム エラー メッセージは、応答の「本文」にあります。

于 2012-08-24T06:13:15.013 に答える