Russ Clark Russ Clark - 9 months ago 94
HTTP Question

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;
UriKind.Absolute, out requestUri);

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create

NetworkCredential nc =
new NetworkCredential("user", "password");

request.Credentials = nc;

request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Answer Source

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);