下载文件请求在服务器上返回 Json 而不是 asp.net web API 中的文件

Utt*_*eja 5 c# iis rest asp.net-mvc asp.net-web-api

我正在尝试在 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;
    }
Run Code Online (Sandbox Code Playgroud)

该文件正在本地主机的浏览器中下载,我在服务器上部署了相同的代码,它在浏览器中返回一个 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
}
Run Code Online (Sandbox Code Playgroud)

我已经检查了 iis 中的 mime 类型及其那里。我错过了什么吗?

Tra*_*ain 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"}
            };
        }
Run Code Online (Sandbox Code Playgroud)

然后对于控制器来说这样调用

public FileResult GeneratePoExportDocument(params)
{

    return GetFile(HostingEnvironment.ApplicationPhysicalPath + "Documents", "\\mydoc.docx");
}
Run Code Online (Sandbox Code Playgroud)

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

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

尝试模仿类型

application/vnd.ms-excel
Run Code Online (Sandbox Code Playgroud)

或者

text/csv
Run Code Online (Sandbox Code Playgroud)