Why does HttpWebRequest throw an exception instead returning HttpStatusCode.NotFound?

后端 未结 2 665
青春惊慌失措
青春惊慌失措 2020-12-09 14:58

I\'m trying to verify the existence of a Url using HttpWebRequest. I found a few examples that do basically this:

HttpWebRequest request = (HttpWebRequest)Ht         


        
相关标签:
2条回答
  • 2020-12-09 15:23

    Ya this can be quite annoying when web pages use status codes heavily and not all of them are errors. Which can make processing the body quite a pain. Personally I use this extension method for getting the response.

    public static class HttpWebResponseExt
    {
        public static HttpWebResponse GetResponseNoException(this HttpWebRequest req)
        {
            try
            {
                return (HttpWebResponse)req.GetResponse();
            }
            catch (WebException we)
            {
                var resp = we.Response as HttpWebResponse;
                if (resp == null)
                    throw;
                return resp;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-09 15:24

    Why not? They're both valid design options, and HttpWebRequest was just designed to work this way.

    0 讨论(0)
提交回复
热议问题