I have been trying to stream a file to my web service. In my Controller(ApiController) I have a Post function as follows:
public void Post(Stream stream)
{
if (stream != null && stream.Length > 0)
{
_websitesContext.Files.Add(new DbFile() { Filename = Guid.NewGuid().ToString(), FileBytes= ToBytes(stream) });
_websitesContext.SaveChanges();
}
}
I have been trying to stream a file with my web client by doing the following:
public void UploadFileStream(HttpPostedFileBase file)
{
WebClient myWebClient = new WebClient();
Stream postStream = myWebClient.OpenWrite(GetFileServiceUrl(), "POST");
var buffer = ToBytes(file.InputStream);
postStream.Write(buffer, 0,buffer.Length);
postStream.Close();
}
Now when i debug my web service, it gets into the Post function, but stream is always null. Was wondering if anyone may have an idea why this is happening?
Web API doesn't model bind to 'Stream' type hence you are seeing the behavior. You could instead capture the incoming request stream by doing: Request.Content.ReadAsStreamAsync()
Example:
Note: you need not even have HttpRequestMessage as a parameter as you could always access this request message via the "Request" property available via ApiController.
You can replace with this code
RestSharp makes this sort of stuff quite easy to do. Recommend trying it out.