簡體   English   中英

Web API 2:文件響應作為 Json 序列化 HttpResponseMessage 返回

[英]Web API 2: File response being returned as Json serialized HttpResponseMessage

我創建了一個 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剛剛被序列化,但沒有包含該文件的內容。 知道這里會發生什么嗎?

先試試這個代碼,你需要在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;
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM