c#WebRequest HttpBehaviour错误

时间:2015-04-30 13:15:57

标签: c# .net c#-4.0 reflection webrequest

我写了一些代码:

this.req = (HttpWebRequest)WebRequest.Create(this._urlNBKIMain);
this.req.Accept = this._accept;
this.req.Headers.Add(this._acceptLanguage);
this.req.UserAgent = this._userAgent;
this.req.Host = this._hostNBKI;
this.req.KeepAlive = this._keepAlive;
this.req.AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate);
this.req.CookieContainer = this.cookieContainer;
ServicePoint servicePoint = this.req.ServicePoint;
PropertyInfo property = servicePoint.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
property.SetValue(servicePoint, 0, null);
this.res = (HttpWebResponse)this.req.GetResponse();

但是,我遇到了运行时错误:

System.ArgumentException: It is not possible to convert an object of type "System.Int32" to type "System.Net.HttpBehaviour".
   in System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
   in System.RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
   in System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
   in System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   in System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   in System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   in System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
   in CheckNBKI.GetMainFormNBKI()

请帮帮我。

1 个答案:

答案 0 :(得分:1)

您正尝试将enum设置为整数值。你应该使用枚举。由于enum不可用(它是.NET Framework的内部),您可以使用一些技巧来获取enum值的实例:

object val = Convert.ChangeType(0, Enum.GetUnderlyingType(property.PropertyType));

property.SetValue(servicePoint, val, null);

我从here获得了一些帮助。