C# WebRequest 返回 401
我的内联网中有一个网络文件,我的计算机有权读取和写入。我可以打开 IE 或 Firefox,通过输入 url 地址来查看该文件。我需要编写一个读取/写入该文件的 C# 桌面应用程序。即使我的计算机可以访问,但迄今为止我的所有尝试都会导致 401、未经授权的访问错误。该程序需要在任何帐户已获得授权的计算机上运行,因此我无法对任何用户名/密码进行硬编码。我从来没有做过这样的事情,但我能够从几个站点中获取以下内容:
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
}
如果重要的话,我正在使用 .NET 2.0
There is a web file within my intranet 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果需要 NTLM 凭据,这将不起作用:
您需要传入实际凭据,例如:
This won't work if NTLM credentials are required:
You need to pass in the actual credentials like:
刚刚遇到了同样的问题,当我添加以下内容时,一切都开始工作:
Just ran into the same problem, it all started working when I added:
您是否尝试使用 Fiddler 检查发送到服务器的实际请求?
您还可以检查服务器是否需要客户端证书才能允许连接。
既然你访问的是内网服务器,那么真的需要设置代理部分吗?我的意思是大多数时候,代理被配置为忽略本地地址。
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.