2011-08-19 74 views
0

我正在使用以下方法來輸出具有其屬性的對象。它適用於大多數對象,但在傳遞HttpRequest對象時拋出。反射 - 爲什麼我無法訪問此HttpRequest屬性?

public static string ConvertToXML(object obj) 
{ 
     if (!obj.GetType().IsPrimitive && obj.GetType() != typeof(String) && obj.GetType() != typeof(Decimal)) 
     { 
      List<string> properties = new List<string>(); 
      foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj)) 
      { 
       string name = descriptor.Name; 
       object value = descriptor.GetValue(obj); 
       properties.Add(xmlify(name, value)); 
      } 
      if (properties.Count == 0) 
       return obj.ToString(); 
      else 
       return xmlify(obj, string.Concat(properties)); 
     } 
     else 
      return obj.ToString(); 
} 

它拋出一個錯誤在這一行:

descriptor.GetValue(obj);

錯誤(對不起,只有德語版:/):

Der Eigenschaftenaccessor HttpChannelBinding für das System.Web.HttpRequest-Objekt hat folgende Ausnahme verursacht: Die Operation wird auf dieser Plattform nicht unterstützt.

它說, HTTPChannelBinding屬性的Property訪問器不支持此平臺上的操作。

這是爲什麼?

+2

你有沒有考慮過使用'obj.GetType()。GetProperties()'?然後你有一個不同的方法調用,'property.GetValue(obj,null)',這可能有一些根本的區別。 – Tejs

回答

2

RTFM ;-) MSDN states在於:

PlatformNotSupportedException - 當前HttpWorkerRequest對象不是System.Web.Hosting.IIS7WorkerRequest對象或System.Web.Hosting.ISAPIWorkerRequestInProc對象。

您不應該認爲讀取任何屬性的值通常不會引發異常。

+0

那麼,我會如何處理這樣的情況呢?抓住例外並繼續前進? – magnattic

+0

這取決於您的代碼的唯一語義。最有可能抓住它,記錄/忽略它,繼續前進。 –

0

我認爲MSDN爲您提供了更多的信息:

拋出PlatformNotSupportedException,如果當前的HttpWorkerRequest對象不是System.Web.Hosting.IIS7WorkerRequest對象或System.Web.Hosting.ISAPIWorkerRequestInProc對象。

它應該可以在Windows Vista(SP1)/ Windows 7或Windwods 2008 Server(核心除外)上工作。 這可能是你的問題。

msdn

相關問題