{"id":116,"date":"2011-08-11T22:05:16","date_gmt":"2011-08-11T14:05:16","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=116"},"modified":"2018-09-02T22:51:43","modified_gmt":"2018-09-02T14:51:43","slug":"handling-web-server-communication-feedback-with-system-net-webexception","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/handling-web-server-communication-feedback-with-system-net-webexception\/","title":{"rendered":"Handling web server communication feedback with System.Net.WebException in C#"},"content":{"rendered":"<p>My previous post on <a href=\"http:\/\/www.techcoil.com\/blog\/2011\/06\/11\/sending-a-file-and-some-form-data-via-http-post-in-c\" target=\"_blank\">sending files via HTTP post<\/a> did not discuss handling of web server communication feedback. Hence, I will do so in this post.  <\/p>\n<p>It is important that a client is able to know if a HTTP request had been successfully processed by the server so that rectification works can be performed. <\/p>\n<h3>Errors that can happen in a HTTP session<\/h3>\n<p>HTTP is a stateless protocol:  <\/p>\n<ol>\n<li>The client sends a HTTP request to the server.<\/li>\n<li>The server process the <a href=\"http:\/\/www.techcoil.com\/blog\/the-http-request-and-how-it-relates-to-system-net-httplistener\/\" title=\"The HTTP request and how it relates to System.Net.HttpListener\" target=\"_blank\">HTTP request<\/a>.<\/li>\n<li>The server sends back a <a href=\"http:\/\/www.techcoil.com\/blog\/the-http-response-and-how-it-relates-to-system-net-httplistener\/\" title=\"The HTTP response and how it relates to System.Net.HttpListener\" target=\"_blank\">HTTP response<\/a> to the client.<\/li>\n<\/ol>\n<p>And all these probably takes place in a TCP\/IP connection maintained by the client and server. With that in mind, it is not difficult to list some of the errors that can happen in a HTTP session:<\/p>\n<ul>\n<li>The web server could not be contacted at all: DNS problems, IP address of machine not reachable, port not opened and etc.<\/li>\n<li>The HTTP request is received by the web server but the web server cannot fulfill the HTTP request: 404 File Not Found, 500 Internal Server Error and etc.<\/li>\n<li>The web server could be contacted initially but terminates the TCP\/IP connection prematurely: uploaded file size limit, web server crashes and etc.<\/li>\n<li>The web server could be contacted but the HTTP response returned by the web server was not complete.<\/li>\n<\/ul>\n<h3>Getting the reasons of HTTP communication failure from System.Net.WebException<\/h3>\n<p>With the error possibilities in mind, we can proceed with handling them from information given in the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.net.webexception.aspx\" target=\"_blank\"><code>System.Net.WebException<\/code><\/a>. Apart from HTTP response with status code 2xx, any other communication feedback will result in a WebException when a HTTP request is sent from the client to the web server. From the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.net.webexception.status.aspx\" target=\"_blank\"><code>Status<\/code><\/a> property defined in the <code>WebException<\/code> class and the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.net.webexceptionstatus.aspx\" target=\"_blank\"><code>System.Net.WebExceptionStatus<\/code><\/a> enumeration, our client program can decide the kind of rectification works to perform:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\ntry\r\n{\r\n    \/\/ Set up the HTTP web request\r\n    HttpWebRequest requestToServer = \r\n        (HttpWebRequest)WebRequest.Create(&quot;http:\/\/www.techcoil.com&quot;);\r\n    requestToServer.Method = WebRequestMethods.Http.Get;\r\n    requestToServer.Credentials = System.Net.CredentialCache.DefaultCredentials;\r\n                \r\n    \/\/ Send the HTTP web request to the server and get the server response\r\n    WebResponse response = requestToServer.GetResponse();\r\n                \r\n    \/\/ The following codes will be executed only if a 2xx HTTP response \r\n    \/\/ is received from the server\r\n    StreamReader responseReader = new StreamReader(response.GetResponseStream());\r\n    \/\/ Get the response body\r\n    string replyFromServer = responseReader.ReadToEnd();\r\n    Console.WriteLine(replyFromServer);\r\n} \r\ncatch (WebException wex) \r\n{\r\n\r\n    \/\/ Exception message and stack trace\r\n    Console.WriteLine(wex.Message);\r\n    Console.WriteLine(wex.StackTrace);\r\n\r\n    \/\/ Inspect the reason of communication failure\r\n    switch (wex.Status)\r\n    {\r\n        case WebExceptionStatus.ConnectFailure:\r\n            \/\/ handle failure to connect to server\r\n            break;\r\n\r\n        case WebExceptionStatus.ReceiveFailure:\r\n            \/\/ handle failure to receive complete\r\n            \/\/ HTTP response from server\r\n            break;\r\n\r\n        case WebExceptionStatus.Timeout:\r\n            \/\/ handle timeout when waiting for\r\n            \/\/ HTTP response from server\r\n            break;\r\n\r\n        case WebExceptionStatus.ConnectionClosed:\r\n            \/\/ handle connection with server closed \r\n            \/\/ prematurely\r\n            break;\r\n\r\n        \/\/ This is where we can examine HTTP status\r\n        \/\/ codes other than 2xx and the server response \r\n        \/\/ body\r\n        case WebExceptionStatus.ProtocolError:\r\n            \/\/ Examine the HTTP response returned\r\n            HttpWebResponse response = (HttpWebResponse)wex.Response;\r\n            StreamReader responseReader = \r\n                new StreamReader(response.GetResponseStream());\r\n            string responseFromServer = responseReader.ReadToEnd();\r\n            switch (response.StatusCode)\r\n            {\r\n                case HttpStatusCode.BadRequest:\r\n                    \/\/ handle bad request (http status code 400)\r\n                    break;\r\n                case HttpStatusCode.InternalServerError:\r\n                    \/\/ handle internal server error (http status code 500)\r\n                    break;\r\n                default:\r\n                    \/\/ handle other http status code returned by\r\n                    \/\/ the server.\r\n                    break;\r\n            } \/\/ end switch(res.StatusCode)\r\n            response.Close();\r\n            break;\r\n\r\n        case WebExceptionStatus.NameResolutionFailure:\r\n            \/\/ handle DNS error\r\n            break;\r\n\r\n        default:\r\n            \/\/ handle other errors not in this switch statement\r\n            break;\r\n    } \/\/ end switch(wex.Status)\r\n} \/\/ end try-catch\r\n<\/pre>\n<h3>Related posts<\/h3>\n<ul>\n<li><a href=\"\/blog\/downloading-a-file-from-via-http-post-and-http-get-in-c\/\" target=\"_blank\">Downloading a file via HTTP post and HTTP get in C#<\/a><\/li>\n<li><a href=\"\/blog\/sending-a-file-and-some-form-data-via-http-post-in-c\/\" target=\"_blank\">Sending a file and some form data via HTTP post in C#<\/a><\/li>\n<li><a href=\"\/blog\/uploading-large-http-multipart-request-with-system-net-httpwebrequest-in-c\/\" target=\"_blank\">Uploading large HTTP multipart request with System.Net.HttpWebRequest in C#<\/a><\/li>\n<li><a href=\"\/blog\/how-to-build-a-web-based-user-interaction-layer-in-c\/\" target=\"_blank\">How to build a web based user interaction layer in C#<\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/deciding-which-http-status-code-to-use-in-a-http-response\/\" title=\"Deciding which HTTP status code to use in a HTTP response\" target=\"_blank\">Deciding which HTTP status code to use in a HTTP response<\/a><\/li>\n<\/ul>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-1S\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-1S&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-1S&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F116&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>My previous post on <a href=\"http:\/\/www.techcoil.com\/blog\/2011\/06\/11\/sending-a-file-and-some-form-data-via-http-post-in-c\" target=\"_blank\">sending files via HTTP post<\/a> did not discuss handling of web server communication feedback. Hence, I will do so in this post.  <\/p>\n<p>It is important that a client is able to know if a HTTP request had been successfully processed by the server so that rectification works can be performed. <\/p>\n","protected":false},"author":1,"featured_media":1189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[20,23,29,28],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/C-Sharp-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-1S","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/116"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=116"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/116\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1189"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=116"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=116"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=116"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}