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

前端 未结 3 1344
滥情空心
滥情空心 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:12

    It helped me (for Unity3d mono, not ASP.Net):

    request.PreAuthenticate = true;
    

    Do not need manual set Authorization header or use CredentialCache.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-11 05:34

    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);
    
    0 讨论(0)
提交回复
热议问题