【发布时间】:2019-11-22 11:49:54
【问题描述】:
我正在尝试在 c# 中使用 Angular 7 和 web api 下载 .xlsx 文件 但我收到此错误:
我的服务.ts
public exportExcelFile(matchedRows: string, reportInfoId: number): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({ 'responseType': 'ResponseContentType.Blob',
'Content-Type': 'application/vnd.ms-excel'})};
const url = `${environment.apiUrl}report/${reportInfoId}/exportExcelFile?matchedRows=${matchedRows}`;
return this.http.get(url, httpOptions);
}
“消耗”我的服务的方法:
exportExcelFile(matchedRows:string){
this.service.exportExcelFile(matchedRows, this.reportInfo.ide).subscribe((response)=>{
console.log(response)
})
this.exportingExcelFile=false;
this.ready=true;
}
从 API 检索我的响应的方法
[HttpGet]
public IHttpActionResult ExportExcelFile(int reportId, bool matchedRows)
{
var user = Request.GetAuthenticatedUser();
var query = new GetExcelFileQuery(reportId, user.UserName, matchedRows);
var result = _dispatcher.Dispatch<GetExcelFileQuery, GetExcelFileModel>(query);
using (var memoryStream = new MemoryStream()) //creating memoryStream
{
result.Workbook.Write(memoryStream);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(memoryStream.ToArray());
response.Content.Headers.ContentType = new MediaTypeHeaderValue
("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = result.FileName
};
return result == null ? NotFound() : (IHttpActionResult)new FileResult(response);
}
}
如果我直接使用浏览器上的 URL 访问,则 Excel 文件已正确导出
【问题讨论】:
标签: c# angular typescript asp.net-web-api