使用 WebClient.UploadFile returns 401 将文件上传到 WebDAV 服务器

Uploading a file to WebDAV server using WebClient.UploadFile returns 401

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

The remote server returned an error: (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
}

问题

由于这个概念只在我的 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>

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

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

身份验证失败可能只是其副作用。即使没有,你解决了认证问题,也可能帮不了你。

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


WinSCP 为您工作时的另一种选择是使用 WinSCP .NET assembly