When running an ASP.NET MVC 4.7 API that exports a PDF file, the application behaves correctly locally, returning the file with a Content-Type of application/pdf. However, upon deployment to a production environment, the Content-Type is unexpectedly set to text/html; charset=utf-8.
[AllowAnonymous]
[HttpGet]
public FileContentResult Export(Guid id, bool? PrintLetterOnly, bool? PrintMentions)
{
var model = Show(id, true);
if (model == null)
return null;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", $"attachment; filename={id}.pdf");
var pdfResult = new ViewAsPdf("export", model)
{
FileName = id + ".pdf",
PageMargins = new Rotativa.Options.Margins(0, 0, 0, 0),
PageSize = Rotativa.Options.Size.A4,
MinimumFontSize = 20,
ContentDisposition = ContentDisposition.Attachment
};
var pdfBytes = pdfResult.BuildFile(this.ControllerContext);
return File(pdfBytes, "application/pdf", id + ".pdf");
}
This API method correctly generates a PDF using Rotativa library and sets the Content-Type to application/pdf. However, in production, despite the correct configuration, the response Content-Type unexpectedly changes to text/html; charset=utf-8, causing the browser to interpret the file as HTML rather than a PDF.
the code from java script for api calling
$("#download").click(function () {
const myHeaders = new Headers();
myHeaders.append("Cookie", "ASP.NET_SessionId=n1q1vjmx2noir5esjdlvjnqb");
const requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow"
};
fetch("/Process/Export/@Model.Id?PrintLetterOnly=True", requestOptions)
.then(response => {
debugger;
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.blob();
})
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = "@(Model.Id).pdf"; // Specify the file name here
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
.catch((error) => console.error(error))
});
I expected the issue from iis server configuration
I think the issue from server configuration or iis configuration not accept to return .pdf
I tried too much ways to convert content type from text/html; charset=utf-8 to application/pdf