2010-09-22 61 views
5

引發異常我發現HttpWebRequest的拋出引發WebException不存在的資源。 在我看來很奇怪,因爲HttpWebResponse具有StatusCode屬性(NotFount項存在)。 你認爲它有什麼理由嗎?或者這只是開發者問題?的HttpWebRequest爲404

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

您調用的API需要在HTTP響應中返回正確的錯誤代碼。聽起來像是一個開發者問題,他們可能沒有正確地捕捉到錯誤。 – RPM1984 2010-09-23 00:00:53

回答

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

試試這個:

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?