.NET Web API中有一个POST端点,用于返回内容中带有byteArray的HttpResponseMessage。
当我使用HttpClient从Angular前端调用终结点并接收响应时,发现该blob的长度与来自终结点的byteArray的大小不匹配。
我试图弄清楚为什么我没有从Content中获取byteArray。我会认为,如果我将响应解析为Blob,则应与我的byteArray的长度匹配。
控制器
[System.Web.Mvc.HttpPost]
public HttpResponseMessage PdfSharpConvert([FromBody] PdfConvertOfficeParams parameters) {
CheckSession();
var data = pDAL.GetPrismClientLocatorOfficeException().Where(v => parameters.PclIds.Contains(Convert.ToInt32(v.ID)));
var sortedData = PrismClientLocatorExceptionService.SortClientLocatorExceptionViews(PrismClientLocatorExceptionService.PrismClientLocatorOfficeExceptionToDictionary(data), parameters.Sort, parameters.FieldName);
var sorteDataDic = PrismClientLocatorExceptionService.DicToClientLocatorOfficeException(sortedData);
var reportText = ReportGenerator.GenerateHtmlReport(sorteDataDic);
try {
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ReportGenerator.ReportPath);
if (System.IO.File.Exists(filePath)) System.IO.File.Delete(filePath);
PdfDocument pdfDoc = PdfGenerator.GeneratePdf(reportText, PageSize.Letter);\
byte[] fileContents = null;
using (MemoryStream stream = new MemoryStream()) {
pdfDoc.Save(stream, true);
fileContents = stream.ToArray();
}
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(fileContents); //OR: new StreamContent(memStream);
return result;
} catch (Exception e) {
throw e;
}
}
角度服务
PdfSharpConvert(pclIds: number[], sort: string, fieldName: string) {
let parameters = { pclIds, sort, fieldName }
let options = new RequestOptions({ responseType: ResponseContentType.Blob });
return this._http.post(this.myAppUrl + 'PrismClient/PdfSharpConvert', parameters, options).pipe(map((response: Response) => response.blob()));
}
角度组件
generateReport(data: number[], sort: string, fieldName: string): void {
this.loading.emit(true);
this._clientService.PdfSharpConvert(data, sort, fieldName).subscribe(
(data) => {
var blob = new Blob([data], { type: "application/pdf" });
FileSaver.saveAs(data, "blobToPdf.html");
},
(error) => {
console.log(error);
this.loading.emit(false);
this.toast({
type: 'error',
title: 'Report has failed to generate'
});
});
}