【问题标题】:Uploading a file to WebDAV server using WebClient.UploadFile returns 401使用 WebClient.UploadFile 将文件上传到 WebDAV 服务器返回 401
【发布时间】:2020-05-06 07:53:26
【问题描述】:

我尝试通过 WebDAV 将文件从 Windows 客户端上的 C# 应用程序上传到 Linux 网络服务器。为此,我使用WebClient.UploadFile()。上传总是抛出异常:

远程服务器返回错误:(401) Unauthorized

我尝试了两种不同的授权方法,结果都一样。

授权:

// Method A
myWebClient.Credentials = new NetworkCredential("user123", "pass123");

// Method B
var bytes = Encoding.UTF8.GetBytes(String.Format("{0}:{1}", "user123", "pass123"));
string auth = Convert.ToBase64String(bytes);
// "Basic aW1hZ2VfdXBsb2FkOkozMkUzYnVGWlB1S0tkQ2tQRkpV"
string authString = String.Format("Basic {0}", auth); 
myWebClient.Headers.Add("Authorization", authString);

为确保 WebDAV 按预期工作,我使用WinSCP(Windows GUI)和cadaver(Linux 终端)连接和上传文件 都成功了


文件上传代码:

try
{
    string address = "http://123.124.125.126/webdav/1";
    string fileName = "F:\\articleimages\\isotope\\1\\1dmgo.jpg";
    byte[] response = myWebClient.UploadFile(address, fileName);
}
catch (WebException wexc)
{
    // wexc.Message == The remote server returned an error: (401) Unauthorized
}

问题

  • 到目前为止我的代码是否正确?
  • 我应该使用哪种授权? NetworkCredentialsHeader?

由于这个概念只在我的 C# 应用程序中失败,问题一定出在那儿。

  • 如何进一步排除故障?

实际响应(异常详情)

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Unauthorized</title>
</head><body>
<h1>Unauthorized</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>

【问题讨论】:

    标签: c# .net winforms apache webdav


    【解决方案1】:

    WebClient 是 HTTP 客户端,而不是 WebDAV 客户端。

    如果你使用WebClient.UploadFile,它默认使用HTTP POST 请求,而不是WebDAV PUT 请求。

    身份验证失败可能只是其副作用。即使没有,并且您解决了身份验证问题,它也可能对您没有帮助。

    我不知道它是否有帮助,但请尝试使用 overload that takes method argument 并使用 "PUT"


    WinSCP 适合您的另一个选项是使用WinSCP .NET assembly

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-16
      • 2013-08-09
      • 1970-01-01
      • 2018-03-12
      • 2023-01-22
      • 1970-01-01
      • 2016-09-07
      • 2023-03-06
      相关资源
      最近更新 更多