InvalidCastException HttpWebRequest c#

时间:2011-09-21 18:49:53

标签: c# windows-phone-7 httpwebrequest background-agent

我遇到了一个问题:当我在BackgroundAgent中创建HttpWebRequest时,app会抛出InvalidCastException。 此代码适用于App前台任务,但在BackgroundAgent中不起作用:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(//InvalidCastException 
              new Uri(url));
          request.BeginGetResponse(r => {
            HttpWebRequest httprequest = (HttpWebRequest)r.AsyncState;
            try {

完整代码:http://pastebin.com/zyCHBQuP

1 个答案:

答案 0 :(得分:1)

返回的类型取决于传递给Create方法的Uri。您将获得一些WebRequest的后代。您必须确保传递的Uri是返回HttpWebRequest的类型,如果您要进行转换,或者您需要在转换之前测试从Create返回的类型或使用as HttpWebRequest。< / p>

http://msdn.microsoft.com/en-us/library/0aa3d588.aspx(适用于.net)

http://msdn.microsoft.com/en-us/library/0aa3d588%28v=VS.95%29.aspx(对于silverlight)