2013-03-11 17 views
7

मैं एक ही बात यहाँ से पूछा के लिए अनिवार्य रूप से देख रहा हूँ पर प्राप्त प्रतिक्रिया शरीर: Any way to access response body using WebClient when the server returns an error?WebClient त्रुटि स्थिति कोड

लेकिन कोई जवाब अब तक उपलब्ध कराए गए हैं।

सर्वर "400 खराब अनुरोध" स्थिति देता है, लेकिन प्रतिक्रिया निकाय के रूप में एक विस्तृत त्रुटि स्पष्टीकरण के साथ।

.NET WebClient के साथ उस डेटा तक पहुंचने पर कोई विचार? जब सर्वर एक त्रुटि स्थिति कोड देता है तो यह सिर्फ अपवाद फेंकता है।

+4

यह अन्य प्रश्न मदद मिल सकती है: http://stackoverflow.com/questions/7036491/get-webclient-errors-as-string –

+0

इस और http://stackoverflow.com/ प्रश्न/11828843/c-sharp-webexception-how-to-get-whole-a-body – I4V

उत्तर

8

आप इसे वेब क्लाइंट से प्राप्त नहीं कर सकते हैं, हालांकि आपके वेबएक्सप्शन पर आप प्रतिक्रिया ऑब्जेक्ट कास्ट कर सकते हैं जो एक HttpWebResponse ऑब्जेक्ट में है और आप संपूर्ण प्रतिक्रिया ऑब्जेक्ट तक पहुंच पाएंगे।

अधिक जानकारी के लिए कृपया WebException कक्षा परिभाषा देखें।

नीचे MSDN से एक उदाहरण है (सबसे अच्छा तरीका अपवाद को संभालने के लिए नहीं है बल्कि यह आपको कुछ पता चलना चाहिए)

try { 
    // Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name. 
    HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site"); 

    // Get the associated response for the above request. 
    HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse(); 
    myHttpWebResponse.Close(); 
} 
catch(WebException e) { 
    Console.WriteLine("This program is expected to throw WebException on successful run."+ 
         "\n\nException Message :" + e.Message); 
    if(e.Status == WebExceptionStatus.ProtocolError) { 
     Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode); 
     Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription); 
    } 
} 
catch(Exception e) { 
    Console.WriteLine(e.Message); 
} 
+0

मुझे पता है कि यह HttpWebRequest का उपयोग कर रहा है लेकिन यह वेब क्लाइंट के लिए समान है क्योंकि सभी विधि वेब अपवाद वापस कर सकती हैं – dmportella

0

आप इस तरह प्रतिक्रिया सामग्री प्राप्त कर सकते हैं:

using (WebClient client = new WebClient()) 
{ 
    try 
    { 
     string data = client.DownloadString(
      "http://your-url.com"); 
     // successful... 
    } 
    catch (WebException ex) 
    { 
     // failed... 
     using (StreamReader r = new StreamReader(
      ex.Response.GetResponseStream())) 
     { 
      string responseContent = r.ReadToEnd(); 
      // ... do whatever ... 
     } 
    } 
} 

परीक्षण किया गया: नेट पर 4.5.2

संबंधित मुद्दे