Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

http - Passing NetworkCredential to HttpWebRequest in C# from ASP.Net Page

I'm trying to use HTTPWebRequest to access a web service, and am having problems passing credentials in, see code below. I can see 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(); 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...