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

前端 未结 3 1347
滥情空心
滥情空心 2020-12-11 05:08

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 i

3条回答
  •  鱼传尺愫
    2020-12-11 05:16

    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.

提交回复
热议问题