简体   繁体   English

下载文件请求返回 JSON 而不是服务器上 ASP.NET Web API 中的文件

[英]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.我正在尝试在 ASP.NET Web API 中下载 CSV 文件。 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 而不是下载文件。

JSON looks like this: JSON 如下所示:

{
  "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.我在 IIS 中检查了 mime 类型,它就在那里。 Am I missing anything ??我错过了什么吗?

This is what usually works for me这通常对我有用

        private ActionResult GetFile(string path, string fileName)
        {
            var memory = new MemoryStream();
            using (var stream = new FileStream(path + fileName, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            memory.Position = 0;
            var file = File(memory, GetContentType(path + fileName), Path.GetFileName(path + fileName));
            file.FileDownloadName = fileName;
            return file;
        }

        private string GetContentType(string path)
        {
            var types = GetMimeTypes();
            var ext = Path.GetExtension(path).ToLowerInvariant();
            return types[ext];
        }
        //find out what .csv is these won't work for you
        private Dictionary<string, string> GetMimeTypes()
        {
            return new Dictionary<string, string>
            {
                //{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }
                //{".docx", "application/vnd.ms-word"}
                //{".pdf", "application/pdf"}
            };
        }

Then for the controller call it like this然后对于控制器来说,像这样调用它

public FileResult GeneratePoExportDocument(params)
{

    return GetFile(HostingEnvironment.ApplicationPhysicalPath + "Documents", "\\mydoc.docx");
}

After that it should automatically download the file.之后它应该会自动下载文件。

Edit: Fix return type for controller method编辑:修复控制器方法的返回类型

Try the mimetypes尝试 mimetype

application/vnd.ms-excel

or或者

text/csv

I ran into this similar problem using WebApi which worked fine locally when debugging in Visual Studio and when deployed to IIS locally.我在使用 WebApi 时遇到了这个类似的问题,在 Visual Studio 中调试和本地部署到 IIS 时,它在本地运行良好。 On my server, I was getting the JSON response as above.在我的服务器上,我得到了上面的 JSON 响应。 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()'.找不到方法:'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>

I faced the similar issue and answer here to another SO question helped me with it.我遇到了类似的问题,在这里回答另一个 SO 问题帮助我解决了这个问题。

Apparently it was the conflicts in System.Net.Http assemblies causing the HttpResponse to behave abnormally.显然是 System.Net.Http 程序集中的冲突导致 HttpResponse 行为异常。 I uninstalled the System.Net.Http nuget package and installed it back.我卸载了 System.Net.Http nuget 包并将其重新安装。 And then I checked in Binding Redirects generated in the web.config .然后我检查了 web.config 中生成的绑定重定向

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM