I have a web api and I would like to post an image file + some data in order to process it correctly when it is received at the server.
The calling code looks something like this:
using(var client = new HttpClient())
using(var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri("http://localhost:8080/");
var fileContent = new ByteArrayContent(File.ReadAllBytes(fileName));
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "foo.jpg"
};
content.Add(fileContent);
FeedItemParams parameters = new FeedItemParams()
{
Id = "1234",
comment = "Some comment about this or that."
};
content.Add(new ObjectContent<FeedItemParams>(parameters, new JsonMediaTypeFormatter()), "parameters");
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
var result = client.PostAsync("/api/ImageServices", content).Result;
And the web api method signature looks like this:
public async Task<HttpResponseMessage> Post([FromBody]FeedItemParams parameters)
When I run this I get an UnsupportedMediaType
exception. I know this has something to do with the ObjectContent
, since this method worked when I was passing just an ID
in the query string instead of the object in the body.
Any ideas where I'm going wrong here?
WebAPI built-in formatters only support the following media types:
application/json
,text/json
,application/xml
,text/xml
andapplication/x-www-form-urlencoded
For
multipart/form-data
, which is what you are sending, take a look at Sending HTML Form Data and ASP.NET WebApi: MultipartDataMediaFormatterSample client
Sample controller if you follow the first article