问题
I am trying to make a request to a web page using WebRequest class in .net. The url that I am trying to read requires Windows Authentication due to which I get an unauthorised exception. How can I pass a windows credentials to this request so that it can authenticate.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( "http://myapp/home.aspx" );
request.Method = "GET";
request.UseDefaultCredentials = false;
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential( "username", "password", "domain" );
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Raises Unauthorized Exception
this.Response.Write( response.StatusCode );
The above code returns the following error.
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
I noticed one thing while checking the exception details is that the url that I am trying to access is redirecting to a different url which is prompting me to provide the NT login details. I believe that the credentials should get forwarded to this url as well. But apparently it is not happening.
回答1:
You should use Credentials property to pass the windows credentials to the web service.
If you wish to pass current windows user's credentials to the service then
request.Credentials = CredentialCache.DefaultCredentials;
should do the trick. Otherwise use NetworkCredential as follows:
request.Credentials = new NetworkCredential(user, pwd, domain);
回答2:
I am trying to access a link A passing the windows credentials. Link A then redirects me to link B automatically but does not pass the windows credentials which I had supplied. Hence the error. I did request.AutoRedirect = false, and looped through every time I get location in the header i.e. I do my redirects manually each time passing the windows credentials.
This worked for me :)
回答3:
For authenticating to WebService, use DefaultNetworkCredentials instead of DefaultCredentials:
request.Credentials = CredentialCache.DefaultNetworkCredentials;
回答4:
Using VS2015, request.UseDefaultCredentials = true; works for me!
来源:https://stackoverflow.com/questions/3562979/making-a-web-request-to-a-web-page-which-requires-windows-authentication