2012-03-02 2 views
1

C#/ asp.netでREST API(クライアント提供)を使用しており、そのREST APIによって返されたjson結果を操作しています。私は次のコードでそれを消費しています。REST APIからHTTPWebRepsonseまでのjsonエラーメッセージの処理

 HttpWebResponse res = null; 
    string ReturnBody = string.Empty; 

    string requestBody = string.Empty; 
       WebRequest request = WebRequest.Create(Path); 
       request.ContentType = "application/json"; 
       request.Method = "POST"; 
       request.ContentLength = json.Length; 

       //Add Basic Auhtentication header 
       string authInfo = Username + ":" + Password; 
       authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); 
       request.Headers["Authorization"] = "Basic " + authInfo; 

       System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream()); 
       sw.Write(json); 
       sw.Close(); 
       res = (HttpWebResponse)request.GetResponse(); 
       if (res != null) 
       { 
        using (StreamReader sr = new StreamReader(res.GetResponseStream(), true)) 
        { 
         ReturnBody = sr.ReadToEnd(); 
         StringBuilder s = new StringBuilder(); 
         s.Append(ReturnBody); 
         sr.Close(); 
        } 
       } 

それが成功コード(200)を返します場合は、それが正しく動作するので、私は、トライcatchブロック内のコードの上に置いてきたので、私はコード

上記のとおり解像度オブジェクトからJSON応答を消費することができますが、そのREST APIがエラーを出すと、それはキャッチするようにリダイレクトされます。resnullになるので、私はFiddlerによって以下の図に示すようにエラーメッセージのjson応答にアクセスできません。

REST test through fiddler

ので、私は自分のコードをそのJSONエラーレスポンスを消費することができる程度どのように私を助けて?

ありがとうございました!助けを求めて

答えて

1

おそらくWebExceptionを取得しています - statusのプロパティを調べてください。あなたの場合、プロトコルエラー、つまり401/403などが表示されます。そのような場合は、Responseプロパティを使用して実際のHTTP応答を取得できます。たとえば、

try 
{ 
    res = (HttpWebResponse)request.GetResponse(); 
    // handle successful response 
    ... 
} 
catch(WebException ex) 
{ 
    if (ex.Status == WebExceptionStatus.ProtocolError) 
    { 
     var response = (HttpWebResponse)ex.Response; 
     // use the response as needed - in your case response.StatusCode would be 403 
     // and body will have JSON describing the error. 
     .. 
    } 
    else 
    { 
     // handle other errors, perhaps re-throw 
     throw; 
    } 
} 
+0

私が探していたのはありがたいことですが、それがelse {thow;}(いくつかの例)に行くときの質問は1つだけです。だから私は元のcatch(例外ex)で適切に処理することができます。 –

+0

@ArunRanaについては、「WebExceptionStatus」の値を参照してください。 - http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus.aspxたとえば、DNSの障害、要求のタイムアウトなどは、他の部分に移動します。 – VinayC

関連する問題