Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file request returning JSON instead of file in ASP.NET Web API on server

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 ??

like image 996
Uttam Ughareja Avatar asked Aug 07 '18 13:08

Uttam Ughareja


People also ask

Does Web API return JSON by default?

After developing the WebAPI we need to host the service for client. There are different types of client with different type requirement. Means some client need result in XML format and same time some client need it JSON format. By default Web API returns result in XML format.

How do I download a file from Web API?

In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.

What is the best approach for requesting JSON instead of XML from API?

Change the default formatter for Accept: text/html to return JSON. This is the top rated answer, and with arguably good reason. This forces ASP.NET Web API to use a JsonFormatter to serialize the response body in the case that a request is made for text/html , the default for most browsers.


1 Answers

I ran into this similar problem using WebApi which worked fine locally when debugging in Visual Studio and when deployed to IIS locally. On my server, I was getting the JSON response as above. After a fresh deploy I was seeing a new error about missing method:

Method not found: 'System.Net.Http.HttpRequestMessage System.Web.Http.Controllers.HttpActionContext.get_Request()'.

The resolution was to add a new binding redirect. Perhaps this is an effective fix for you.

  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.2.0.0" />
  </dependentAssembly>
like image 95
cbedrosian Avatar answered Oct 25 '22 20:10

cbedrosian