I'm trying to download CSV file in ASP.NET Web API. Here is my code, and it's working in local.
[Route("{name?}")]
public HttpResponseMessage Get(string name = "DownloadFile")
{
name = name.EndsWith(".csv") ? name : $"{name}.csv";
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write("Hello, World!");
writer.Flush();
stream.Position = 0;
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.Add("x-filename", name);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = name
};
return result;
}
The file is being downloaded in browser in localhost. I deployed the same code on the server and it's returning a JSON in the browser instead of downloading a file.
JSON looks like this:
{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"key": "x-filename",
"value": [
"test.csv"
]
},
{
"key": "Content-Type",
"value": [
"application/octet-stream"
]
},
{
"key": "Content-Disposition",
"value": [
"attachment; filename=test.csv"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"requestMessage": null,
"isSuccessStatusCode": true
}
I've checked mime type in IIS and it's there. Am I missing anything ??