繁体   English   中英

无法下载文件

[英]Trouble downloading a file

我正在尝试从C#应用程序下载文件。 我尝试了两种不同的方法,但是都产生了相同的响应:“远程服务器返回了错误:(401)未经授权。”

我很确定这是一个凭据问题(由于401)。 如果我从浏览器导航到URL,然后输入提供的完全相同的凭据,则文件下载就很好。 在“尝试2”(如下)中,对于authtype,我尝试过:NTLM,Basic,Negotiate和Digest,但没有任何运气。

有人看到我在这里做错了吗?

谢谢您的帮助!

尝试1:

string username = "username";
string password = "password";
string domain = "domain";
string url = @"http://LiveLinkInstance.com/livelink/llisapi.dll/999999/WordDocument.docx?func=doc.Fetch&nodeid=999999&ReadOnly=True&VerNum=-2&nexturl=/livelink/llisapi.dll?func=ll&objId=888888&objAction=browse&viewType=1";  

// Create an instance of WebClient
WebClient client = new WebClient();
client.Proxy = null;

client.Credentials = new System.Net.NetworkCredential(username, password, domain);

client.DownloadFile(new Uri(url), @"C:\FileDownloads\test.txt");

尝试2:

string username = "username";
string password = "password";
string domain = "domain";
string url = @"http://LiveLinkInstance.com/livelink/llisapi.dll/999999/WordDocument.docx?func=doc.Fetch&nodeid=999999&ReadOnly=True&VerNum=-2&nexturl=/livelink/llisapi.dll?func=ll&objId=888888&objAction=browse&viewType=1";

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);

string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(domain + "\\" + username + ":" + password));
wr.Headers.Add("Authorization", "Basic " + credentials);

CredentialCache cc = new CredentialCache();
cc.Add(new Uri(url), "NTLM", new NetworkCredential(username, password, domain));
wr.Credentials = cc;
Stream str = ws.GetResponseStream();

你试过了吗

client.UseDefaultCredentials = true 

如果您使用的是MVC或WebApi,则应使用

[Authorize]

如果您可以假冒用户,请像这样使用它

 WindowsIdentity wi = null;
 wi = (WindowsIdentity)HttpContext.Current.User.Identity;

 using (wi.Impersonate())
       {
         var client = new WebClient { UseDefaultCredentials = true };

         client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
            var result = JsonConvert.DeserializeObject<Object>(Encoding.UTF8.GetString(client.DownloadData("http://api.com/api/values")));

         return Request.CreateResponse(result);
       }

正如Amitay所说,使用Fiddler与浏览器的流量进行比较是最好的方法。 顺便说一句,看看这里的SO -发生了什么是OP的情况是,请求被重定向到不同的位置,但凭据没有重新通过。 因此,OP进行了手动重定向来解决此问题。

我看到LL使用了自己的基于表单的身份验证或基于IWA的SSO。 我不知道您是否可以使用其他HTTP身份验证类型。

如果您的服务器使用(默认)表单身份验证,则必须使用LAPI或WS下载在LAPI / WS调用中提供LL凭证的文档。 您也可以通过LAPI / WS获得用于HTTP通信的cookie。

如果已配置SSO,则可以将Credentials设置为CredentialCache.DefaultCredentials以传入当前已认证的Windows会话的凭据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM