【问题标题】:Web API 2: File response being returned as Json serialized HttpResponseMessageWeb API 2:文件响应作为 Json 序列化 HttpResponseMessage 返回
【发布时间】:2020-01-09 11:36:36
【问题描述】:

我创建了一个 ASP.NET Web API 2 控制器 POST 方法,该方法返回一个包含 csv 文件的 HttpResponseMessage。不幸的是,当我尝试从我的 Angular 应用程序中使用此方法时,响应始终是HttpResponseMessage 的序列化版本。

控制器方法:

[Route("club/{clubId}/audience/export/csv")]
[HttpPost]
[ProducesResponseType(typeof(HttpResponseMessage), 200)]
public async Task<HttpResponseMessage> ExportAudienceCSV([FromRoute] int clubId, [FromBody]EmailInput emailInput)
{
   return await this.GenerateCsv($"AudienceExport_{DateTime.UtcNow:HHmmssddMMyy}",
         () => _commsServices.ExportAudienceCSV(clubId, emailInput));
}

我使用包含 csv 数据的流创建HttpResponseMessage 的方法(在此之前该流被重置为位置 0):

public static async Task<HttpResponseMessage> GenerateCsv(this BaseController controller,
    string fileName,
    Func<Task<MemoryStream>> fileGenerator)
{
  var reportStream = await fileGenerator.Invoke();

  var result = new HttpResponseMessage(HttpStatusCode.OK)
  {
     Content = new StreamContent(reportStream)
  };

  result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
  {
     FileName = $"{fileName}.csv"
  };

  result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  result.Content.Headers.ContentLength = reportStream.Length;

  return result;
}

请求方法如下所示:

POST http://localhost:51056/api/v1/comms/club/2/audience/export/csv HTTP/1.1
Host: localhost:51056
Connection: keep-alive
Content-Length: 121
Origin: http://localhost:5000
AppTimezoneOffset: 0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36
Content-Type: application/json
Accept: application/json, text/plain, */*
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Referer: XXXXXXXXXXXXXXXXXXX
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,en-GB;q=0.8

{"audience":[{"series":378,"divisions":[],"subseries":[],"races":[],"includeSkippers":true,"includeAllBoatAdmins":true}]}

回复是这样的:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Vary: Origin
Server: Kestrel
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:5000
Access-Control-Expose-Headers: *
Request-Context: appId=cid-v1:73955d83-a87e-4968-b6b4-5878f10f9dab
X-Powered-By: ASP.NET
Date: Thu, 09 Jan 2020 11:17:57 GMT
Content-Length: 416

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=AudienceExport_111755090120.csv"]},{"key":"Content-Type","value":["application/octet-stream"]},{"key":"Content-Length","value":["5915"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

如您所见,HttpResponseMessage 刚刚被序列化,但没有包含该文件的内容。知道这里可能发生了什么吗?

【问题讨论】:

标签: c# .net asp.net-web-api asp.net-web-api2


【解决方案1】:

试试这个代码 首先,您需要在 Stream 中创建一个文件。

  public HttpResponseMessage GenrateFile(Stream stream, string fileName)
  {
        HttpResponseMessage response;
        response = Request.CreateResponse(HttpStatusCode.OK);
        MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("text/csv");
        response.Content = new StreamContent(stream);
        response.Content = response.Content;
        response.Content.Headers.ContentType = mediaType;
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = fileName;
        return response;
   }

【讨论】:

    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多