user2330270 user2330270 - 4 months ago 48
C# Question

Content-Disposition is always null in web api 2

I have a very simple form:

<form id="upload" enctype="multipart/form-data" action="~/Api/File/Post" method="post" >
<input type="file" name="files[0].media" />
<input type="submit" value="Submit" />

When debugging I get the file, but
is always null so I can not access the file name. I dont see any other property in the Request object to get the file name.

What confuses me the most is inspecting the request with chromes debugger shows the following details

Content-Type:multipart/form-data; boundary=----WebKitFormBoundary3rLRRBQX6jj7MbWU
Content-Disposition: form-data; name="files[0].media"; filename="MyFileName.mp4"
Content-Type: video/mp4


Any ideas? This looks like it is being sent correctly... (removed file name in example above)


Given the html form provided in your question you should be able to access the file data using the following code:

public async Task<IHttpActionResult> Post()
    if (!Request.Content.IsMimeMultipartContent())
        return this.StatusCode(HttpStatusCode.UnsupportedMediaType);

    var filesProvider = await Request.Content.ReadAsMultipartAsync();
    var fileContents = filesProvider.Contents.FirstOrDefault();
    if (fileContents == null)
        return this.BadRequest("Missing file");

    var headers = fileContents.Headers;
    string filename = headers.ContentDisposition.FileName;
    Stream fileStream = await fileContents.ReadAsStreamAsync();

    ... do something with the file name and stream