网络客户端下载文件访问被拒绝

本文关键字:拒绝 访问 文件 客户端 下载 网络 | 更新日期: 2023-09-27 18:31:35

我正在尝试将文件下载到服务器,但数据被写入错误。请告诉我出了什么问题。当我在"http://localhost:xxx"上使用此代码时,一切正常。 WebClient myWebClient = new WebClient(); myWebClient.DownloadFile(remoteUri, Server.MapPath("~/test/" + "test.xml"));

更新了我的问题。这是我的完整代码:

string path1 = "certificate1.p12";
string path2 = "certificate2.crt";
X509Certificate2 cert1 = new X509Certificate2(Server.MapPath(("~/test/") + path1), "", X509KeyStorageFlags.MachineKeySet);
X509Certificate2 cert2 = new X509Certificate2(Server.MapPath(("~/tets/") + path2));
CertificateWebClient2 myWebClient = new CertificateWebClient2(cert1, cert2);
string remoteUri = "https://xxxxx";
string path = "test.xml";
myWebClient.UseDefaultCredentials = true;
myWebClient.DownloadFile(remoteUri, Server.MapPath((@"~/Files/") + path));

public class CertificateWebClient : WebClient
{
    private readonly X509Certificate2 certificate1;
    private readonly X509Certificate2 certificate2;
    public CertificateWebClient(X509Certificate2 cert1, X509Certificate2 cert2)
    {
        certificate1 = cert1;
        certificate2 = cert2;
    }
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
        {
            return true;
        };
        request.ProtocolVersion = HttpVersion.Version10;
        request.Method = "Post";
        request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
        request.ContentType = "application/x-www-form-urlencoded";
        request.UseDefaultCredentials = true;
        request.ContentLength = 0;
        request.ClientCertificates.Add(certificate1);
        request.ClientCertificates.Add(certificate2);
        return request;
    }
}

网络客户端下载文件访问被拒绝

检查下载是否被代理服务器阻止。如果是这样,请使用以下代码:

using (var webClient = new WebClient())
{
    //  Obtain the 'Proxy' of the  Default browser.
    IWebProxy webProxy = webClient.Proxy;
    if (webProxy != null)
    {
        // Use the default credentials of the logged on user.
        webProxy.Credentials = CredentialCache.DefaultCredentials;
    }
   // Do stuff
}

我想你没有使用凭据。当您使用浏览器加载时,它会自动附加它,但不会附加到 Web 客户端。

因此,您需要使用默认凭据。https://msdn.microsoft.com/en-us/library/system.net.webclient.usedefaultcredentials(v=vs.110).aspx

但是 Web 服务器应该使用正确的用户。

尝试使用默认凭据。

WebClient myWebClient = new WebClient { UseDefaultCredentials = true };
myWebClient.DownloadFile(remoteUri, Server.MapPath("~/test/" + "test.xml"));