HttpWebRequest throws an exception for 404

I found that HttpWebRequest throws a WebException for non-existing resources. It seems very strange to me, because HttpWebResponse has the StatusCode property (the NotFount element exists). Do you think this has any reason for this, or maybe it's just a developers problem?

var req = (HttpWebRequest)WebRequest.Create(someUrl);
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) {
    if (response.StatusCode == HttpStatusCode.OK) { ...}
}
+5
source share
2 answers

This is a really disappointing issue that can be circumvented by using the following extension method class and calling request. BetterGetResponse ()

//-----------------------------------------------------------------------
//
//     Copyright (c) 2011 Garrett Serack. All rights reserved.
//
//
//     The software is licensed under the Apache 2.0 License (the "License")
//     You may not use the software except in compliance with the License.
//
//-----------------------------------------------------------------------

namespace CoApp.Toolkit.Extensions {
    using System;
    using System.Net;

    public static class WebRequestExtensions {
        public static WebResponse BetterEndGetResponse(this WebRequest request, IAsyncResult asyncResult) {
            try {
                return request.EndGetResponse(asyncResult);
            }
            catch (WebException wex) {
                if( wex.Response != null ) {
                    return wex.Response;
                }
                throw;
            }
        }

        public static WebResponse BetterGetResponse(this WebRequest request) {
            try {
                return request.GetResponse();
            }
            catch (WebException wex) {
                if( wex.Response != null ) {
                    return wex.Response;
                }
                throw;
            }
        }
    }
}

Read more about this in my blog post on this topic http://fearthecowboy.com/2011/09/02/fixing-webrequests-desire-to-throw-exceptions-instead-of-returning-status/

+3

:

var req = (HttpWebRequest)WebRequest.Create(someUrl);
req.Method = "Head";

using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) {
    if (response.StatusCode == HttpStatusCode.OK) { ...}
}

WebRequest System.Net.WebException 404, ?

+1

All Articles