问题
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();
回答1:
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
回答2:
Have you tried setting the Credentials object on the request with proper authorization for the server you are trying to access? See System.Net.NetworkCredential.
回答3:
Try checking on both production and dev iis the authentication methods for the application (iis manager -> click on the website->features view ->authentication).
Sounds like on the dev iis you have anonymous authentication enabled, and on production iis not. If you will not have anonymous auth enabled on production, you will probably need to set the request.Credentials as you can see above.
来源:https://stackoverflow.com/questions/14184199/receiving-the-remote-server-returned-an-error-403-forbidden-message