【发布时间】: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
}
问题
- 到目前为止我的代码是否正确?
- 我应该使用哪种授权?
NetworkCredentials或Header?
由于这个概念只在我的 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