I had a more difficult variation of this, using Puppeteer Sharp. I needed both Headers and Cookies set before the download would start.
In essence, before the button click, I had to process multiple responses and handle a single response with the download. Once I had that particular response, I had to attach headers and cookies for the remote server to send the downloadable data in the response.
await using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Product = Product.Chrome }))
await using (var page = await browser.NewPageAsync())
{
...
// Handle multiple responses and process the Download
page.Response += async (sender, responseCreatedEventArgs) =>
{
if (!responseCreatedEventArgs.Response.Headers.ContainsKey("Content-Type"))
return;
// Handle the response with the Excel download
var contentType = responseCreatedEventArgs.Response.Headers["Content-Type"];
if (contentType.Contains("application/vnd.ms-excel"))
{
string getUrl = responseCreatedEventArgs.Response.Url;
// Add the cookies to a container for the upcoming Download GET request
var pageCookies = await page.GetCookiesAsync();
var cookieContainer = BuildCookieContainer(pageCookies);
await DownloadFileRequiringHeadersAndCookies(getUrl, fullPath, cookieContainer, cancellationToken);
}
};
await page.ClickAsync("button[id^='next']");
// NEED THIS TIMEOUT TO KEEP THE BROWSER OPEN WHILE THE FILE IS DOWNLOADING!
await page.WaitForTimeoutAsync(1000 * configs.DownloadDurationEstimateInSeconds);
}
Populate the Cookie Container like this:
private CookieContainer BuildCookieContainer(IEnumerable<CookieParam> cookies)
{
var cookieContainer = new CookieContainer();
foreach (var cookie in cookies)
{
cookieContainer.Add(new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain));
}
return cookieContainer;
}
The details of DownloadFileRequiringHeadersAndCookies are here. If your needs to download a file are more simplistic, you can probably use the other methods mentioned on this thread, or the linked thread.