I'm trying to use HTTPWebRequest to access a web service, and am having problems passing credentials in, see code below. I can s开发者_如何转开发ee the credentials object, nc, being built in the debugger, and also in the assignment to request.Credentials, but when I get to the last line of code it faults with a not authorized error message. I've had our server folks watch the request on the server, and there are no credentials being passed. Am I doing something wrong with the Credentials object, or is there something I need to do that I'm not doing here?
Uri requestUri = null;
Uri.TryCreate("https://mywebserver/webpage"), 
    UriKind.Absolute, out requestUri);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create
    (requestUri);
NetworkCredential nc =
    new NetworkCredential("user", "password");
request.Credentials = nc;
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
The NetworkCredentials are either extremely non-intuitive, or flaky, or both. Regardless, you can solve the issue by bypassing NetworkCredentials altogether and use this method (which I found, courtesy of mark.michaelis.net)
/* http://mark.michaelis.net/Blog/CallingWebServicesUsingBasicAuthentication.aspx */
byte[] credentialBuffer = new UTF8Encoding().GetBytes(username + ":" +password);
req.Headers["Authorization"] ="Basic " + Convert.ToBase64String(credentialBuffer);
So what you're doing is manually creating a header for your HttpWebRequest and inserting the content as it would appear in a Basic Authentication header. Works like a charm.
Microsoft Premier Support finally helped me solve this problem by using the CredentialCache class to add the Credentials and the "Basic" authorization:
NetworkCredential nc =
    new NetworkCredential(GetSetting("username"), GetSetting("password"));
CredentialCache cache = new CredentialCache();
cache.Add(requestUri, "Basic", nc);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
It helped me (for Unity3d mono, not ASP.Net):
request.PreAuthenticate = true;
Do not need manual set Authorization header or use CredentialCache.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论