+1 on what Radim has mentioned above...As per your action Web API model binding notices that the parameter fileContents
is a complex type and by default assumes to read the request body content using the formatters. (note that since fileName
and description
parameters are of string
type, they are expected to come from uri by default).
You can do something like the following to prevent model binding to take place:
[HttpPost]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UploadFile")]
public async Task UploadFile(string fileName, string description)
{
byte[] fileContents = await Request.Content.ReadAsByteArrayAsync();
....
}
BTW, what do you plan to do with this fileContents
? are you trying to create a local file? if yes, there is a better way to handle this.
Update based on your last comment:
A quick example of what you could do
[HttpPost]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UploadFile")]
public async Task UploadFile(string fileName, string description)
{
Stream requestStream = await Request.Content.ReadAsStreamAsync();
//TODO: Following are some cases you might need to handle
//1. if there is already a file with the same name in the folder
//2. by default, request content is buffered and so if large files are uploaded
// then the request buffer policy needs to be changed to be non-buffered to imporve memory usage
//3. if exception happens while copying contents to a file
using(FileStream fileStream = File.Create(@"C:\UploadedFiles\" + fileName))
{
await requestStream.CopyToAsync(fileStream);
}
// you need not close the request stream as Web API would take care of it
}