【问题标题】:Download file request returning JSON instead of file in ASP.NET Web API on server下载文件请求返回 JSON 而不是服务器上 ASP.NET Web API 中的文件
【发布时间】:2019-01-14 15:28:37
【问题描述】:

我正在尝试在 ASP.NET Web API 中下载 CSV 文件。 这是我的代码,它在本地工作。

[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;
}

文件正在本地主机的浏览器中下载。 我在服务器上部署了相同的代码,它返回一个 JSON 在浏览器中而不是下载文件。

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
}

我在 IIS 中检查了 mime 类型,它就在那里。 我错过了什么吗??

【问题讨论】:

  • 您返回的是响应而不是文件
  • 是的,但这在 locahost 上按预期工作
  • 我面临同样的问题。 @UttamUghareja,你找到解决方案了吗?
  • 很遗憾,没有,我会尽快发布我的答案

标签: c# asp.net-mvc rest iis asp.net-web-api


【解决方案1】:

我遇到了类似的问题,并回答 here 对另一个 SO 问题帮助了我。

显然是 System.Net.Http 程序集中的冲突导致 HttpResponse 行为异常。我卸载了 System.Net.Http nuget 包并将其重新安装。然后我签入了 web.config 中生成的绑定重定向

【讨论】:

    【解决方案2】:

    我在使用 WebApi 时遇到了类似的问题,当在 Visual Studio 中调试和本地部署到 IIS 时,它在本地运行良好。在我的服务器上,我收到了上面的 JSON 响应。重新部署后,我看到一个关于缺少方法的新错误:

    找不到方法:'System.Net.Http.HttpRequestMessage System.Web.Http.Controllers.HttpActionContext.get_Request()'。

    解决方案是添加一个新的绑定重定向。也许这对您来说是一个有效的解决方法。

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

    【讨论】:

      【解决方案3】:

      这通常对我有用

              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"}
                  };
              }
      

      然后为控制器这样调用它

      public FileResult GeneratePoExportDocument(params)
      {
      
          return GetFile(HostingEnvironment.ApplicationPhysicalPath + "Documents", "\\mydoc.docx");
      }
      

      之后它应该会自动下载文件。

      编辑:修复控制器方法的返回类型

      尝试模仿类型

      application/vnd.ms-excel
      

      text/csv
      

      【讨论】:

      • 已经尝试过这些尝试 mimetypes。我正在寻找关于 web api 的解决方案
      猜你喜欢
      • 2018-05-18
      • 2019-08-03
      • 1970-01-01
      • 2012-02-26
      • 2023-04-05
      • 2011-07-07
      • 1970-01-01
      • 2012-06-20
      相关资源
      最近更新 更多