1

I have a webapi controller code looks like:

        [HttpPost]
    public HttpResponseMessage DownloadForms(FormCriteria criteria)
    {
        string downloadData = new FormsToCsvHelper(Umbraco, criteria).GetCsv();
        return Request.CreateResponse(HttpStatusCode.OK, downloadData);
    }

If i look at the data returned in debugger just before sending it back it looks like:

Created Date,IP,Form Name,Email address,Message,Full Name

31/05/2019 10:43:08,127.0.0.1,Contact form - test,test12@hotmail.com,test,Ismail Mayat

If I copy and paste it into file and save as csv it looks fine in excel.

However the data i actually get back looks like:

"Created Date,IP,Form Name,Email address,Message,Full Name\r\n31/05/2019 10:43:08,127.0.0.1,Contact form - test,test12@hotmail.com,test,Ismail Mayat"

The whole record set it wrapped in quote and the line feed is seen as a literal so when opening file in excel its all on one line.

There is a DelegatingHandler that fire but that is for a specific url request so for this request it does not do anything.

Anyone any ideas whats going on?

1 Answer 1

5

WebAPI will serialize the value as JSON by default, so that's why your value is enclosed in double quotes.

To get around this, you can use the StringContent class:

return new HttpResponseMessage(statusCode) {
    Content = new StringContent(downloadData, Encoding.UTF8, "text/csv")
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.