开发者

C# WebRequest returning 401

开发者 https://www.devze.com 2023-01-16 12:35 出处:网络
There is a web file within my intranet开发者_如何学Go that my computer is authorized to read and write. I can open up IE or Firefox and view the file by typing int the url address. I need to write a C

There is a web file within my intranet开发者_如何学Go that my computer is authorized to read and write. I can open up IE or Firefox and view the file by typing int the url address. I need to write a C# desktop app that reads/writes to that file. Even though my computer has access, all my attempts so far result in 401, unauthorized access errors. The program needs to work from any computer whose account has been authorized, so I cannot hard-code any username/password. I've never done anything like this, but I was able to scrounge the following from several sites:

WebRequest objRequest = HttpWebRequest.Create("https://site.com/file");
objRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
objRequest.Proxy = WebRequest.DefaultWebProxy;
objRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;

WebResponse objResponse = (WebResponse)objRequest.GetResponse();

using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
    string str = sr.ReadToEnd();
    sr.Close();
    //... Do stuff with str
}

If it matters, I'm working in .NET 2.0


Just ran into the same problem, it all started working when I added:

objRequest.UseDefaultCredentials = true;


Did you try using Fiddler to inspect the actual request that was sent to the server? You can also check if the server requires a client certificate to allow the connection.

Since you are accessing an intranet server, do you really need to set the proxy part? I mean most of the time, the proxy is configured to ignore local addresses anyway.


This won't work if NTLM credentials are required:

objRequest.Credentials = CredentialCache.DefaultNetworkCredentials;

You need to pass in the actual credentials like:

NetworkCredential networkCredential = new NetworkCredential(UserName, Password, Domain);
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(url), "NTLM", networkCredential);
objRequest.Proxy.Credentials = credCache;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号