我正在尝试创建一个API调用到我的服务器,以允许我上传一个 .csv 文件。
客户端代码
string url = "http://testserver/testapi";
string filePath = @"C:\test.csv";
using (WebClient wc = new WebClient())
{
wc.Headers.Add("Content-Type", "text/plain");
byte[] responseArray = wc.UploadFile(url, filePath);
}
服务器端代码
string savePath = testSavePath;
foreach (string f in Request.Files.AllKeys)
{
HttpPostedFileBase file = Request.Files[f];
file.SaveAs(savePath);
}
我在这一行代码
byte[] responseArray = wc.UploadFile(url, filePath);
中遇到了一个异常。奇怪的是,当我查看
Request
时,我看到了ContentType="multipart/form-data; boundary=---------------------8d006b7c2a5452c"
。查看UploadFile文档后,我发现当
Content-type header
以multipart开头时,会抛出WebException异常。我的问题是为什么
contentType
会被设置为multipart,如何防止它这样做?
wc.Headers.Add("Content-Type", "text/plain");
,它还能正常工作吗? - Lee Gunn