Bir web sunucusu, HttpWebRequest.GetResponse()
HTTP 304 (Değiştirilmemiştir) ile yanıt verirse, GetResponse()
, bana çok garip olan bir WebException
. Bu tasarıma mı bağlı, yoksa burada bariz bir şey eksik mi?HttpWebRequest.GetResponse, WebException öğesini HTTP 304'te atar
cevap
Tamam, bu bir tasarım davranışını ve vexing exception'un mükemmel bir örneği gibi görünüyor. Bu, bu ile çözülebilir:
public static HttpWebResponse GetHttpResponse(this HttpWebRequest request)
{
try
{
return (HttpWebResponse) request.GetResponse();
}
catch (WebException ex)
{
if(ex.Response == null || ex.Status != WebExceptionStatus.ProtocolError)
throw;
return (HttpWebResponse)ex.Response;
}
}
Bu gerçekten sinir bozucu bir sorundur ve alternatif 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;
}
}
}
}
okumak aşağıdaki uzatma yöntemi sınıfını kullanarak ve çağrılarak geçici olarak alınabilir http://fearthecowboy.com/2011/09/02/fixing-webrequests-desire-to-throw-exceptions-instead-of-returning-status/
yolu bu konuda benim blog yazısı bu konuda daha fazla bu System.WebException
false
için AllowAutoRedirect özelliğini ayarlamaktır önlemek için. Bu, WebRequest
'un otomatik yönlendirme mantığını devre dışı bırakır. 304 yönlendirme istekleri için kırılmış gibi gözüküyor, çünkü en katı anlamda gerçek bir yönlendirme değil. Elbette diğer yönlendirme istekleri 3xx
el ile ele alınması gerektiği anlamına gelir.
Kesinlikle harika. İhtiyacım olmasa, ağır elle kullanılan istisna makineleri için neden ödeme yapmalıyım? – jsuddsjr
Ben de koduyla bu konuya rastladım:
try
{
...
var webResponse = req.GetResponse();
...
}
catch (WebException ex)
{
Log.Error("Unknown error occured", ex);
//throw;
}
Ve Uzak Sunucu bu hatayı atma veya özel 304 döndürerek o tarayıcıya geçirilmelidir 304 durumunu dönerse bu yüzden Tarayıcı geri dönebilirler anlaşılmaktadır önbelleğe alınmış yanıt. Aksi takdirde, muhtemelen Uzak Sunucudan Yanıtı boşaltabilirsiniz. Sadece bir Bilginize olarak
try
{
...
var webResponse = req.GetResponse();
...
}
catch (WebException ex)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotModified)
throw;
Log.Error("Unknown error occured", ex);
}
, bu C# 6 (VS2015) when
maddesini kullanan Anton Gogolev's answer için bir güncelleme:
public static HttpWebResponse GetHttpResponse(this HttpWebRequest request)
{
try
{
return (HttpWebResponse) request.GetResponse();
}
catch (WebException ex)
when (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
{
return (HttpWebResponse) ex.Response;
}
}
- 1. UserAgent öğesini http isteği
- 2. Spark, java.util.NoSuchElementException öğesini atar: anahtar bulunamadı: 67
- 3. akka http atar EntityStreamException: Varlık akışı kesme
- 4. Http Angular2 çocuk sınıfı hata atar
- 5. WebException Hatası Hata numarasını alın
- 6. Xamarin iOS, büyük bir yerel kitaplık yüklendiğinde System.TypeInitializationException öğesini atar
- 7. GetResponse WebException ve ex.Response null'ı atıyor
- 8. WebException bir WebException'ın yanıt akışını okurken
- 9. AWS İstemcisi ile Symfony 3, AnnotationException ("@http" açıklaması) atar
- 10. filled.contour hata atar
- 11. Sözlük, Add veya ContainsKey üzerinde bir IndexOutOfRangeException öğesini ne zaman atar?
- 12. preg_replace bölüm hatası atar
- 13. recursive_directory_iterator istisnayı atar
- 14. Regex.Match, FormatException'ı atar
- 15. bir atar hata msg
- 16. atar eleme hata
- 17. BeginInvoke, istisna atar
- 18. sqlite.net PCL, TypeInitalizationException'ı atar
- 19. _CRT_DEBUGGER_HOOK istisna atar
- 20. android - MediaRecorder, illegalalstateexception'ı atar
- 21. JavaFx Programı, java.lang.reflect.InvocationTargetException'ı atar.
- 22. Kafka, java.nio.channels.ClosedChannelException'ı atar
- 23. HTTPWebRequest.GetResponse(), kimliği doğrulanmış bir proxy aracılığıyla kimliği doğrulanmış isteklerde başarısız oluyor
- 24. validate() ağaç NullPointerException L & F değişikliğine atar?
- 25. CodeRay Raylar hatayı atar konsol
- 26. xaml içinde Özel RoutedUICommand kullanma istisnayı atar
- 27. JavaScript: JSLint Oku" atar Sadece
- 28. Filtre operatörü derleyici hatası atar
- 29. shortcut, Intellij Idea'ye bildirim atar
- 30. Gson.fromJson() - Type farklıysa istisna atar
Bu en vakaların çalışır fakat bir 404 hatası döndürürken bazı web sunucuları bir cevap gövdesini geri dönebilirler. Bu durumda, yukarıdaki kod bir 304'ü tedavi ettiği için bir 404'ü tedavi edecektir! – comshak
@comshak, "bilmek güzel." Çağrı kodu, kabul edilebilir cevap kodlarının farkında olmalıdır. – roufamatic
Ben de eklendi || ((HttpWebResponse) ex.Response) .StatusCode! = HttpStatusCode.NotModified' –