Since this simplistic test worked (passing a string in the body):
Server code:
public string PostArgsAndFile([FromBody] string value, string serialNum, string siteNum)
{
string s = string.Format("{0}-{1}-{2}", value, serialNum, siteNum);
return s;
}
Client code:
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);
}
}
...I then tried to take it a step further (toward what I really need to do - send a file, not a string); I changed the server code to this:
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;
}
...and the client code to this:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var result = client.UploadFile(uri, @"C:\MiscInWindows7\SampleXLS.csv");
}
...but that dies at runtime with:
System.Net.WebException was unhandled HResult=-2146233079 Message=The remote server returned an error: (415) Unsupported Media Type.
So how can I receive a file uploaded this way? What media type do I need, and how do I specify it?
UPDATE
As I need to ultimately send a file, or at least the contents of a file, I found this SO Question/Answer and changed my code to be:
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));
}
...and although that shows me that byteData is correctly assigned to, nothing seems to be going to the server - the server's "value" property:
public void PostArgsAndFile([FromBody] byte[] value, string serialNum, string siteNum)
...is just an empty byte array when the method is called.
I tried removing the [FromBody], to no avail (no change), and changing it to [FromUri] (which I didn't think would work, but tried it on a lark) caused it to crash with a WebException.
So how do I get the server to accept/recognize/receive the byte array?