WebClient generates (401) Unauthorized error

后端 未结 5 1909
予麋鹿
予麋鹿 2020-12-06 09:14

I have the following code running in a windows service:

WebClient webClient = new WebClient();
webClient.Credentials = new NetworkCredential(\"me\", \"12345\         


        
5条回答
  •  余生分开走
    2020-12-06 09:35

    Hmm. Lots of answers, but I wonder if answering your last question would have solved everything. "me" is not an authorization type (unless your server has added support for it, of course!). You probably want "Basic".

    Also keep in mind that some webservices require you to send the authorization header on the initial request, and this won't do that. Rather it responds with it after getting an authorization required response from the server. If you need this, you need to create your own Authorization header.

    String basicToken = Base64Encoding.EncodeStringToBase64(String.Format("{0}:{1}", clientId.Trim(), clientSecret.Trim()));
    
    webClient.Headers.Add("Authorization", String.Format("Basic {0}", basicToken));
    

    And of course as people have pointed out, setting UseDefaultCredentials to true works if you are using IIS (or other windows security aware http server) in a windows environment.

提交回复
热议问题