Reflection - Why can't I access this HttpReque

2019-09-04 14:29发布

问题:

I am using the following method to output objects with their properties. It works great with most objects, but throws when I pass a HttpRequest object.

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();
}

It throws an error in this line:

descriptor.GetValue(obj);

The error (sorry, only have the german version :/):

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

It says that the Property accessor for the HTTPChannelBinding property does not support the operation on this platform.

Why is that?

回答1:

RTFM ;-) MSDN states that:

PlatformNotSupportedException — The current HttpWorkerRequest object is not a System.Web.Hosting.IIS7WorkerRequest object or a System.Web.Hosting.ISAPIWorkerRequestInProc object.

You should not assume that reading a value of generally any property can't throw an exception.



回答2:

I think MSDN gives you more info:

Throws PlatformNotSupportedException, if The current HttpWorkerRequest object is not a System.Web.Hosting.IIS7WorkerRequest object or a System.Web.Hosting.ISAPIWorkerRequestInProc object.

It should work on Windows Vista (SP1)/ Windows 7 or Windwods 2008 Server (except core). This may be your Problem.

msdn