从Web API {H 44}返回HttpResponseMessage中的字节数组时为空白PDF

时间:2017-02-16 01:48:38

标签: javascript c# jquery ajax xmlhttprequest

所以我有这个奇怪的问题,我试图显示我从我的网络API收到的pdf,但pdf在Chrome的新浏览器标签中显示为空白(IE显示什么,但它是console.logs ajax成功回调)。

API将其发送回我的ajax请求,如下所示:

public async Task<HttpResponseMessage> GetPdf(PdfModel model)
        {
            var pdf = await _pdfManager.GetPdfAsync(model);

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new ByteArrayContent(pdf);
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = "MyPdf.pdf";
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

            return response;
        }

这是GetPdfAsync方法,它调用另一个API来获取pdf。当我使用Postman使用相同的模型调用api时,我会得到一个显示为响应的PDF,所以我知道它工作正常。

public async Task<byte[]> GetPdfAsync(PdfModel, CancellationToken ct = new CancellationToken())
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = PdfGeneratorApiUrl;

                var content = JsonConvert.SerializeObject(model);
                const string endpoint = "myPdf/pdf";

                var response = await client.PostAsync(endpoint, new StringContent(content, Encoding.UTF8, "application/json"), ct);

                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsByteArrayAsync();
                }
                else
                {
                    return null;
                }
            }
        }

在我的ajax调用中,这就是我试图显示它的方式,但是当我在新选项卡中打开pdf时,它会显示一个空白的pdf,其中包含我在ajax成功时给出的文件名。虽然在console.log中blob.size = 1053248。

 $.ajax({
         url: '/n/api/getPdf',
         type: 'POST',
         contentType: 'application/json',
         responseType: 'arraybuffer',
         data: JSON.stringify(getPdfRequest),
         success: function (data) {
             var blob = new Blob([data]);
             console.log(blob.size);
             var link=document.createElement('a');
             link.href=window.URL.createObjectURL(blob);
             link.download="MyPdf.pdf";
             link.click();
         },
         error: function (data) {
             console.log(data);
         }
  });

0 个答案:

没有答案
相关问题