代码之家  ›  专栏  ›  技术社区  ›  Danil

HttpWebrequest正在引发404的异常

  •  5
  • Danil  · 技术社区  · 15 年前

    我发现HttpWebRequest正在为不存在的资源投递WebExpRebug。 在我看来很奇怪,因为HttpWebResponse有StaseCal码属性(NoTunt项目存在)。 你认为这有什么原因吗?也许只是开发人员的问题?

    var req = (HttpWebRequest)WebRequest.Create(someUrl);
    using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) {
        if (response.StatusCode == HttpStatusCode.OK) { ...}
    }
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   Garrett Serack    14 年前

    这确实是一个令人沮丧的问题,可以通过使用以下扩展方法类和调用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;
                }
            }
        }
    }
    

    你在我的博客上看到了更多关于这个主题的信息 http://fearthecowboy.com/2011/09/02/fixing-webrequests-desire-to-throw-exceptions-instead-of-returning-status/

        2
  •  1
  •   Community Mohan Dere    9 年前

    试试这个:

    var req = (HttpWebRequest)WebRequest.Create(someUrl);
    req.Method = "Head";
    
    using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) {
        if (response.StatusCode == HttpStatusCode.OK) { ...}
    }
    

    WebRequest and System.Net.WebException on 404, slow?

    推荐文章