【发布时间】:2014-02-25 23:50:58
【问题描述】:
由于这个简单的测试有效(在正文中传递一个字符串):
服务器代码:
public string PostArgsAndFile([FromBody] string value, string serialNum, string siteNum)
{
string s = string.Format("{0}-{1}-{2}", value, serialNum, siteNum);
return s;
}
客户端代码:
private void ProcessRESTPostFileData(string uri)
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString(uri, "POST", data);
MessageBox.Show(result);
}
}
...然后我尝试更进一步(朝着我真正需要做的事情 - 发送文件,而不是字符串);我将服务器代码更改为:
public string PostArgsAndFile([FromBody] byte[] value, string serialNum, string siteNum)
{
byte[] bite = value;
string s = string.Format("{0}{1}{2}", value.ToString(), serialNum, siteNum);
return s;
}
...和客户端代码:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var result = client.UploadFile(uri, @"C:\MiscInWindows7\SampleXLS.csv");
}
...但是在运行时会死掉:
System.Net.WebException 未处理 H结果=-2146233079 Message=远程服务器返回错误:(415) Unsupported Media Type。
那么我怎样才能接收以这种方式上传的文件呢?我需要什么媒体类型,如何指定?
更新
由于我最终需要发送一个文件,或者至少是一个文件的内容,我找到了this SO Question/Answer并将我的代码更改为:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(@"C:\MiscInWindows7\SampleXLS.csv"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
string allLines = sb.ToString();
byte[] byteData = UTF8Encoding.UTF8.GetBytes(allLines);
byte[] responseArray = client.UploadData(uri, byteData);
// Decode and display the response.
MessageBox.Show("\nResponse Received.The contents of the file uploaded are:\n{0}",
System.Text.Encoding.ASCII.GetString(responseArray));
}
...虽然这表明 byteData 已正确分配给我,但似乎没有任何东西进入服务器 - 服务器的“值”属性:
public void PostArgsAndFile([FromBody] byte[] value, string serialNum, string siteNum)
...在调用方法时只是一个空字节数组。
我尝试删除 [FromBody],但无济于事(没有更改),并将其更改为 [FromUri](我认为这不起作用,但在百灵鸟上尝试过)导致它崩溃并出现 WebException .
那么如何让服务器接受/识别/接收字节数组呢?
【问题讨论】:
标签: asp.net-web-api http-headers webclient system.net.webexception media-type