从 base64string c# 响应 PDF 下载

Response PDF download from base64string c#

我正在尝试做一个 API 下载 PDF,我做的是这样的:

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 不是问题。

如有任何建议,我们将不胜感激。谢谢

尝试使用 ByteArrayContent:

HttpResponseMessage result = new HttpResponseMessage();
try 
{
    byte[] pdfBytes = System.IO.File.ReadAllBytes(pdfLocation);
    result.StatusCode = HttpStatusCode.OK;
    result.Content = new ByteArrayContent(pdfBytes );
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "BuildingDetail.pdf" };

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