I've created a new project using visual studio templates to describe my problem.
New project information template information:
Blazor Web App.
Framework: .NET 8.0 (Long Term Support)
Authentication type: None
Configure for HTTPS: true
Interactive render mode: Server
Interactivity location: Per page/component
Include sample pages: true
Do not use top-level statements: true
I add a PDF (HiMom.pdf) to my wwwroot folder.
I write this code in Home.razor:
@page "/"
@inject IWebHostEnvironment _webHostEnvironment
<PageTitle>Home</PageTitle>
<object type="application/pdf" data="@($"data:application/pdf;base64,{base64PdfString}")" style="position:absolute; left: 0; top: 0;" width="100%" height="100%"/>
@code {
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
private string? base64PdfString = null;
protected override void OnInitialized()
{
if (HttpContext != null)
{
HttpContext.Response.Headers.Append("content-disposition", "inline; filename=MyCustomName.pdf");
}
var pdfFilePath = Path.Combine(_webHostEnvironment.WebRootPath, "HiMom.pdf");
var pdfBlob = System.IO.File.ReadAllBytes(pdfFilePath);
base64PdfString = Convert.ToBase64String(pdfBlob);
}
}
In Home.razor I render a PDF.
In my real application I read a PDF as a byte array from the database.
I simulate this by converting a local PDF file to a byte array.
When I start the application the browser opens the PDF.
This is all good.
However, when the browser opens the PDF I can choose to save the PDF.
This opens a dialog where the filename is always download.pdf.
I want to be able to set this filename from my code. How can I do that?
As you can see I tried doing it using HttpContext and setting content-disposition header.