Gilles Gilles - 11 months ago 103
C# Question

Sending a model containing files from an MVC site to a Web Api site

I have an ASP.Net MVC site that allows the user to subtmit a form along with uploading files.

This part works. But in my MVC Post method, I need to call an ASP.Net Web API method and pass it the model.

This is the part I don't know how to do.

Here is my model in my MVC App:

public class MyModel
public DateTime SubmittedDate { get; set; }
public string Comments { get; set; }
public IEnumerable<HttpPostedFileBase> Files { get; set; }

In my MVC site I have the following method:

public async Task<ActionResult> Details(MyModel model)
if (!ModelState.IsValid)
// the rest of the method

In this method the files and model are correctly populated. When I put a breakpoint and navigate over the Files property I can see the correct number of files with the correct names and file types.

In my Details method, I want to call a method on another site which is a Web API site.

Here is the method on the Web API site:

public HttpResponseMessage Foo(MyModel myModel)
// do stuff

Normally in my MVC method I would call the Web API using the
class using the

But when I do:

HttpResponseMessage response = await httpClient.PostAsJsonAsync(urlServiceCall, myModel);

I receive this error:


Additional information: Error getting value from 'ReadTimeout' on

Answer Source

That is because it is trying to serialize the input stream of the files. I would suggest creating a new model for the web api that have the stream as byte arrays.

public class PostedFile {
    public int ContentLength { get; set; }
    public string ContentType { get; set; }
    public string FileName { get; set; }
    public byte[] Data { get; set; }

public class WebApiModel {
    public DateTime SubmittedDate { get; set; }
    public string Comments { get; set; }
    public List<PostedFile> Files { get; set; }

the serializer would do better with the arrays than the stream.