HttpWebRequest为404抛出异常

时间:2010-09-22 15:47:16

标签: asp.net

我发现HttpWebRequest正在为不存在的资源抛出WebException。 在我看来非常奇怪,因为HttpWebResponse具有StatusCode属性(存在NotFount项)。 你认为它有任何原因,或者它只是开发人员的问题吗?

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

2 个答案:

答案 0 :(得分:3)

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

的关于此主题的博文中了解更多相关信息

答案 1 :(得分:1)

试试这个:

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?