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

问题描述 投票:2回答:1

我试图通过WebDAV将Windows客户端上的C#应用程序中的文件上传到Linux Webserver上。为了达到这个目的,我使用了 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个回答
1
投票

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

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

认证失败可能只是一个副作用。而且即使不是,你解决了认证问题,可能也帮不了你。

我不知道能不能帮到你,但可以尝试用一个 超载 method 争论 并使用 "PUT".


另一个选择,因为WinSCP对你有用,是使用 WinSCP .NET汇编.

© www.soinside.com 2019 - 2024. All rights reserved.