SevenDays
SevenDays

Reputation: 3768

InvalidCastException HttpWebRequest c#

I have a problem: app throws InvalidCastException when I creating HttpWebRequest in BackgroundAgent. This code works in App foreground tasks, but doesn't works in BackgroundAgent:

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

Full code: http://pastebin.com/zyCHBQuP

Upvotes: 1

Views: 657

Answers (1)

The type returned is dependent on the Uri passed into the Create method. You will get some descendant of WebRequest. You must be sure the Uri you pass is of the type that will return an HttpWebRequest if you are going to make that cast, or you will need to test the type returned from Create prior to casting or use the as HttpWebRequest.

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

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

Upvotes: 1

Related Questions