Inherited some legacy code and need to fix a bug using a specific method (described in post title).
Backend ASP.Net controller return HttpResponseMessage type containing PDF. This code is unmodified and worked with the anchor tag.
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(buffer);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
Frontend: Anchor tag with href attribute previosly calls the C# API endpoint directly. This is new code that I set up for this AJAX solution:
//Primary call site that kicks it off:
JavaScriptAPILayer.GetMyPDF(args).done(function (model) {
let a = document.createElement("a");
a.href = "data:application/pdf,"+model;
a.download = "documentName.pdf"
a.click();
})
//AJAX client options that call the C# endpoint and ideally return a PDF type.
...(options?.isPDF ? {'contentType': 'application/pdf'} : {'contentType': 'application/json; charset=utf-8'}),
...(options?.isPDF ? {} : {'dataType': 'json'}),
...(options?.isPDF ? {'data': data} : {'data': data ? JSON.stringify(data) : undefined}),
I would like to use Ajax to call the endpoint, and inject the returned PDF object into a new window, tab, HTML element, download, etc. When I open the PDF, a standard browser error is displayed. When I inspect the contents, I see incorrectly encoded/decoded data.
Why this approach: the bug will be fixed if I call the C# endpoint using JavaScriptAPILayer. The client and subroutines in the JS layer contain business logic that can not be moved to the C# layer.
Detailed description of solution attempt (S.O. prescribed):
The JS AJAX client calls the C# endpoints. The C# endpoints already return PDF data types. This works with the anchor tag. To make it work with AJAX, I modified the JS client to return PDF specific contentTypes/dataTypes. Previous the JS client was used for JSON only. I set up a JS call site to call the JS -> C# API layers. The header changes and call site did enable me to successfully download a PDF, but it appears to be incorrectly encoded/decoded.