问题
I'm calling a webAPI web service that uses windows authentication. I'm using this code in my development environment since I am developing from a box that is not on the domain.
var req = (HttpWebRequest)WebRequest.Create(url);
req.Credentials = new NetworkCredential("username", "password", "domain");
req.Method = WebRequestMethods.Http.Post; //or get
This works just fine when I do a post, but when I want to do a get it doesn't work.
When i visit the url for the get in a web browser it asks for my username and password, as expected. I enter the username and password correctly and the GET works.
回答1:
Try basic authentication as below:
string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
req.Headers.Add("Authorization", authorization);
来源:https://stackoverflow.com/questions/19851474/networkcredential-working-for-post-but-not-get