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

6

我正在尝试在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类型,它是存在的。 有什么我漏掉的吗??


你正在返回响应而不是文件 - Md. Abdul Alim
1
是的,但在本地主机上这正常工作。 - Uttam Ughareja
我也遇到了同样的问题。@UttamUghareja,你找到解决方案了吗? - navigator
很遗憾,我会在找到合适的解决方案后尽快发布我的答案。 - Uttam Ughareja
3个回答

1
我在使用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>

0

这通常对我有用

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

然后它应该自动下载文件。

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

尝试使用MIME类型

application/vnd.ms-excel

或者

text/csv

已经尝试过这些,请尝试使用MIME类型。我正在寻找Web API的解决方案。 - Uttam Ughareja

0

我遇到了类似的问题,另一个SO问题上这里的答案帮助了我。

显然是System.Net.Http程序集中的冲突导致HttpResponse表现异常。我卸载了System.Net.Http Nuget包并重新安装它。然后我在web.config中检查生成的绑定重定向


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接