1

I am developing an MVC ApiController that manages the serialization of uploaded files.

I access the content of the uploaded file with this method:

public class UploadController : ApiController
{
    [System.Web.Http.HttpPost]
    public UploadOutcome UploadFile()
    {
        HttpContent selectFile = Request.Content;
        UploadOutcome res = null;

        //implements the serialization logic
        SerializerManager serializer = new SerializerManager();

        try
        {
            string content = selectFile.ReadAsStringAsync().Result;
            res = serializer.Serialize(content);
        }
        catch(Exception ex)
        {
            throw ex;
        }

        return res;
    }
}

The Request.Content.ReadAsStringAsync().Result is a widely used solution. See here and here.

Unfortunately the obtained content string contains both the content and the headers of the HttpRequestMessage:

File content

920-006099 ;84;65;07/03/2014 00:00;13/03/2014 23:59;10;BZ;1
RL60GQERS1/XEF;1499;1024;07/03/2014 00:00;13/03/2014 23:59;5;KV;1

Content string

-----------------------------11414419513108
Content-Disposition: form-data; name="selectFile"; filename="feed.csv"
Content-Type: text/csv

920-006099 ;84;65;07/03/2014 00:00;13/03/2014 23:59;10;BZ;1
RL60GQERS1/XEF;1499;1024;07/03/2014 00:00;13/03/2014 23:59;5;KV;1
-----------------------------11414419513108--

QUESTION

Is there a way to get rid of the headers? In other words, I want to get the content without the headers.

Community
  • 1
  • 1
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
  • You could use `HttpPostedFile` as a parameter on your method. What you get from `Content` is effectively the body. It just happens to have the headers repeated in the content, together with the file. – Kenneth Mar 14 '14 at 13:50
  • 1
    @Kenneth, not for Web API, which ADC is evidently using. – Kirk Woll Mar 14 '14 at 14:02

1 Answers1

2

You should use ReadAsMultipartAsync:

var content = await selectFile.ReadAsMultipartAsync(); // You *really* ought to be using await
var body = await content.Contents.Single(x => x.Headers.ContentDisposition.Name == "\"selectFile\"").ReadAsStringAsync();

Your content (without the headers) will be in body. To use await, you should change your method signature to:

public async Task<UploadOutcome> UploadFile()
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
  • Unfortunately `await` is not available in MVC4. Tags updated. – Alberto De Caro Mar 14 '14 at 14:08
  • @ADC, that is not true: http://byterot.blogspot.com/2012/03/aspnet-web-api-series-part-2-async.html If you are using *.Net 4.0*, rather than 4.5, that would be true. In that case, my answer is the same, but you can get it synchronously like you did in your original question. – Kirk Woll Mar 14 '14 at 14:13