Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'System.Net.FileWebRequest' can not be casted to 'System.Net.HttpWebRequest' on remote machine, but works locally

I am getting the error when trying from a server (deployed the same code on the server):

Unable to cast object of type 'System.Net.FileWebRequest' to type 'System.Net.HttpWebRequest'

But when I am trying to use the same code from my local machine, it is not giving error.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

Any idea guys what could be wrong?

like image 479
alice7 Avatar asked Jan 17 '11 23:01

alice7


2 Answers

The URI being passed in is not an http URI -- it's either just a path or a file URI. Ensure the URI starts with http:. If it's a relative URI, you'll need to make it absolute.

like image 121
Jeffrey Hantin Avatar answered Nov 19 '22 06:11

Jeffrey Hantin


WebRequest is the type returned by WebRequest.Create() factory method, and is an abstract type.

According to the protocol recognized in the URL string, it returns you a valid subclass, like FileWebRequest or FtpWebRequest.

The problem in your code is that you are trying to create a request for a local file (file://) protocol, so the factory returns FileWebRequest, but you are forcing the code to think it's are remote HTTP URL. Simply wrong.

This explains the fact that it works only with remote and not local files

like image 43
usr-local-ΕΨΗΕΛΩΝ Avatar answered Nov 19 '22 07:11

usr-local-ΕΨΗΕΛΩΝ