dblh90
dblh90

Reputation: 173

Casting between object type of ' FileWebRequest ' to ' HttpRequest '

Good evening guys

I'm new here in this forum, and I need you to help me

Am working on a project that send a file of XML, and I'm using HTTPRequest, I faced an error like this:

Unable to cast object of type 'System.net.FileWebRequest' to type 'System.net.HTTPWebrequest'

![enter image description here][1]

public string POST(string URL, string MsgXML)
{
  string Response = null;
  try
  {

    Request = (HttpWebRequest)HttpWebRequest.Create(URL);
    Request.Method = "POST";
    Request.ContentType = "text/xml";
    byte[] bodyBytes = Encoding.UTF8.GetBytes(MsgXML);
    Request.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
    Request.GetRequestStream().Close();

    using (var res = (HttpWebResponse)Request.GetResponse() as HttpWebResponse)
    {
      StreamReader Rdr = new StreamReader(res.GetResponseStream());
      Response = Rdr.ReadToEnd();
      Rdr.Close();
      Rdr = null;
      return Response;
    }
  }
}

And that was the method of posting I used.

And I dnt know what to do, please Help me guys :)

Upvotes: 1

Views: 4721

Answers (1)

Ani
Ani

Reputation: 113472

From WebRequest.Create, which is the actual method you are calling (the compiler lets you get away with calling a static method "through" a derived class):

[..] when a URI beginning with http:// or https:// is passed in requestUri, an HttpWebRequest is returned by Create. If a URI beginning with ftp:// is passed instead, the Create method will return a FileWebRequest instance. If a URI beginning with file:// is passed instead, the Create method will return a FileWebRequest instance.

You have two options, basically:

  1. Write your method so that it will work for any kind of URI, including file resources.
  2. Validate that the string represents a URI that is a resource accessed over http (for example, with Uri.Scheme).

Upvotes: 2

Related Questions