我想使用Angular6和WebAPI下载PDF。
这是代码实现,
支原体

download(myObj: any) {
    this.testService.downloadDoc(myObj.id).subscribe(result => {

        var url = window.URL.createObjectURL(result);
        window.open(url);
        console.log("download result ", result);
    });
}

MyServices
downloadDoc(Id: string): Observable<any> {
    let url = this.apiUrl + "api/myApi/download/" + Id;
    return this.http.get(url, { responseType: "blob" });
}

Web API服务
[HttpGet("download/{DocId}")]
    public async Task<HttpResponseMessage> GetDocument(string docId)
    {
        var docDetails = await _hoaDocs.GetDocumentDetails(docId).ConfigureAwait(false);
        var dataBytes = docDetails.Stream;
        var dataStream = new MemoryStream(dataBytes);

        var response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            Content = new StreamContent(dataStream)
        };

        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = docDetails.File_Name
        };
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

        return response;
    }

当我执行上面的代码时,它并没有下载pdf,下面是控制台中记录的result对象
download result
Blob(379) {size: 379, type: "application/json"}
size:379
type:"application/json"
__proto__:Blob

最佳答案

我假设您使用的是.NET Core。
返回类型为HttpResponseMessage。对于.NET Core以后的版本,它应该是iactionResult。
所以,在你的情况下,你会回来

return File(<filepath-or-stream>, <content-type>)


您必须在startup.cs文件中做一个小更改:
services.AddMvc().AddWebApiConventions();

那么,我在这里不是百分之百确定,但你也必须改变路线:
routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");

07-24 09:43