NetworkCredential working for POST but not GET

2019-08-09 15:59发布

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条回答
叼着烟拽天下
2楼-- · 2019-08-09 16:46

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);
查看更多
登录 后发表回答