I am receiving "The remote server returned an error: (403) Forbidden" error message on the block of code below. Specifically this line is failing: var response = (HttpWebResponse)(request.GetResponse());
The code works perfectly on my dev machine, but not in production. I am using IIS 7.5 in both environments. Both machines are fulling patched (all Windows updates installed). Using 4.0 .Net Framework. Not sure why it works on one machine and not other other.
Code:
var uri = new Uri(url);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Timeout = System.Threading.Timeout.Infinite;
request.Method = @"POST";
request.ContentType = @"application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.UserAgent = @"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)";
request.Accept = "*/*";
//setup the stream variables and do the send/retrieve of data
Stream writeStream = request.GetRequestStream();
var bytes = System.Text.Encoding.ASCII.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
var response = (HttpWebResponse)(request.GetResponse());
var responseStream = response.GetResponseStream();
var readStream = new StreamReader(responseStream, Encoding.UTF8);
pageResponse = readStream.ReadToEnd();
You might need to specify credentials
request.Credentials = CredentialCache.DefaultCredentials;
or you if you need to pass specific credentials pass:
request.Credentials = new NetworkCredentials("user", "password");
More information about NetworkdCredential Class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With