2010-09-22 31 views
5

Tôi đã tìm thấy HttpWebRequest đang ném WebException cho các tài nguyên không tồn tại. Dường như với tôi rất lạ khi HttpWebResponse có thuộc tính StatusCode (mục NotFount tồn tại). Bạn có nghĩ rằng nó có bất kỳ lý do cho điều đó hoặc có thể nó chỉ là vấn đề phát triển?HttpWebRequest là ném ngoại lệ cho 404

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

API bạn đang gọi cần trả lại mã lỗi chính xác trong phản hồi HTTP. nghe có vẻ giống như vấn đề của nhà phát triển đối với tôi, có thể họ không gặp lỗi đúng cách. – RPM1984

Trả lời

3

Đây thực sự là một vấn đề bực bội, có thể được giải quyết bằng cách sử dụng các lớp mở rộng phương pháp sau và gọi 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; 
      } 
     } 
    } 
} 

Bạn đọc thêm về nó trong bài viết trên blog của tôi trên chủ đề này tại http://fearthecowboy.com/2011/09/02/fixing-webrequests-desire-to-throw-exceptions-instead-of-returning-status/

1

Hãy thử điều này:

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?

Các vấn đề liên quan