在我們公司的內部網中有一臺服務器,負責存儲文件。最初,服務器只能在Intranet環境中運行,但現在需要與外部Web應用程序共享文件。使該服務器可以從互聯網訪問不是一種選擇。使用WebClient獲取內部網文件
我想創建一個ASP.NET MVC解決方案,它使用WebClient從Intranet服務器獲取這些文件,並通過外部應用程序的FileResult將它們發回給用戶。該客戶端將提供自定義域用戶憑證。到目前爲止,我已經嘗試創建一個CredentialCache類,設置正確的憑據,並把它添加到Web客戶證書屬性像下面的代碼:
public ActionResult Download(int id, string fileName)
{
var fileService = new FilesService();
var documentUrl = fileService.GetUrlFileByFileId(id);
string filePath = "http://my.intranet.com/" + documentUrl;
var fileNameFromUrl = filePath.Substring(filePath.LastIndexOf("\\") + 1);
byte[] filedata;
CredentialCache cc = new CredentialCache();
cc.Add(new Uri("http://my.intranet.com/"),
"ntlm",
new NetworkCredential("myUserName", "myPassword", "myDomain"));
using (var client = new WebClient())
{
client.Credentials = cc;
filedata = client.DownloadData(filePath);
}
string contentType = MimeMapping.GetMimeMapping(filePath);
var cd = new ContentDisposition
{
FileName = fileName,
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
根據張貼在Domain credentials for a WebClient class don't work它應該工作的問題,但事實並非如此。它只在我在本地主機上運行問題時運行,但是當我在測試服務器上發佈我的解決方案時,它會返回401錯誤。我的問題是如何得到這個工作?有沒有可能通過這種方法下載文件?
更新---我已經在另一臺服務器上發佈了我的測試應用程序,它開始工作。現在測試應用程序位於另一臺服務器上,而不是存儲文件的服務器。任何想法爲什麼它們都不在同一臺機器上時工作?
是的,我確定。域中的每個用戶都可以訪問所有文件,因此使用哪個帳戶無關緊要。 –