【问题标题】:Using WebClient to get a intranet files使用WebClient获取内网文件
【发布时间】:2017-04-06 00:11:15
【问题描述】:

在我们的公司内部网中有一个服务器,负责存储文件。最初,服务器只能在 Intranet 环境中运行,但现在需要与外部 Web 应用程序共享文件。无法从 Internet 访问此服务器。

我想创建一个 ASP.NET MVC 解决方案,它使用 WebClient 从 Intranet 服务器获取这些文件并通过外部应用程序的 FileResult 将它们发送回用户。该客户端将提供自定义域用户凭据。到目前为止,我已经尝试创建一个 CredentialCache 类,设置正确的凭据并将其附加到 WebClients Credentials 属性,如下面的代码所示:

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 中发布的问题,它应该可以工作,但事实并非如此。只有当我在 localhost 上运行问题时它才会运行,但是当我在测试服务器上发布我的解决方案时,它会返回 401 错误。我的问题是如何让这个工作?是否可以通过这种方式下载文件?

更新---我已经在另一台服务器上发布了我的测试应用程序,它开始工作了。现在测试应用程序位于存储文件的服务器之外的另一台服务器上。任何想法为什么当两者都在同一台机器上时它不起作用?

【问题讨论】:

    标签: asp.net asp.net-mvc webclient windows-authentication


    【解决方案1】:

    401 错误是未经授权的,因此问题可能与权限有关。您确定您用于登录该文件夹的用户帐户具有适当的访问权限吗?

    【讨论】:

    • 是的,我确定。域中的每个用户都可以访问所有文件,因此我使用的帐户无关紧要。
    【解决方案2】:

    好的,我在这个网站上找到了解决方案:https://blogs.msdn.microsoft.com/distributedservices/2009/11/10/wcf-calling-wcf-service-hosted-in-iis-on-the-same-machine-as-client-throws-authentication-error/

    解决方案是添加一个注册表项并将我的 Web 应用程序添加到该项以允许反向连接。

    【讨论】:

      猜你喜欢
      • 2013-12-27
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多