响应PDF从base64string下载C#

时间:2018-09-12 03:22:05

标签: c# pdf memorystream

我正在尝试制作一个用于下载PDF的API,我所做的就像这样:

HttpResponseMessage result = new HttpResponseMessage();
MemoryStream stream = new MemoryStream();
try {
    var base64 = "...";
    byte[] pdfBytes = Convert.FromBase64String(base64);

    stream = new MemoryStream(pdfBytes);

    var resultPDF = Encoding.UTF8.GetString(stream.ToArray());

    result.StatusCode = HttpStatusCode.OK;
    result.Content = new StringContent(resultPDF);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "BuildingDetail.pdf" };

} catch (Exception e) {
    stream.Close();
    result.StatusCode = HttpStatusCode.InternalServerError;
    result.ReasonPhrase = e.Message;// "Error occured while exporting csv file!";
} finally {
    stream.Close();
}

当我尝试测试API时,它可以下载,但PDF为空。

我还试图复制base64字符串并由其他免费来源decode and download网站解码,看来工作正常,因此使base64不再是问题。

对此的任何建议将不胜感激。谢谢。

0 个答案:

没有答案