ScreenshotNeo

BlogHow-to

How to Fix Rotativa BuildFile Not Calling the Action Method

Fix Rotativa BuildFile when your action breakpoint is never hit, the PDF is blank, or authentication and deployment settings are wrong.

By the ScreenshotNeo team30 September 20266 min read

How to Fix Rotativa BuildFile Not Calling the Action Method

Short answer: a Rotativa BuildFile call usually misses the action because the application is using the wrong Rotativa package, lacks a live ControllerContext, does not forward authentication cookies, or cannot find the wkhtmltopdf binaries. Check those causes in that order.

1. Confirm the framework and package

The original Rotativa package is for classic ASP.NET MVC (System.Web) and uses result types such as ActionAsPdf. ASP.NET Core uses the separate Rotativa.AspNetCore package, where ViewAsPdf and BuildFile are documented. Mixing the APIs can produce incompatible result and context types.

Application Package/API Typical result Context
ASP.NET MVC (System.Web) Rotativa ActionAsPdf, ViewAsPdf ControllerContext; forward forms-auth cookies for protected actions
ASP.NET Core Rotativa.AspNetCore ViewAsPdf this.ControllerContext; deploy wkhtmltopdf binaries

See the classic MVC project and the ASP.NET Core project documentation for the package-specific APIs.

2. Classic ASP.NET MVC: pass cookies and a live context

Call BuildFile from a controller action so a valid ControllerContext exists. If the target action requires forms authentication, copy the incoming cookies to the internal request and set the forms-authentication cookie name.

BuildFile needs the same context and authentication data as the original request.
BuildFile needs the same context and authentication data as the original request.
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Rotativa;

public class ReportsController : Controller
{
    public void SaveAsPdf()
    {
        var cookies = Request.Cookies.AllKeys
            .ToDictionary(key => key, key => Request.Cookies[key].Value);

        var report = new ActionAsPdf("DetailsAll")
        {
            FileName = "report.pdf",
            FormsAuthenticationCookieName = FormsAuthentication.FormsCookieName,
            Cookies = cookies
        };

        byte[] pdf = report.BuildFile(ControllerContext);
        File.WriteAllBytes(Server.MapPath("~/App_Data/report.pdf"), pdf);
    }

    [Authorize]
    public ActionResult DetailsAll()
    {
        return View(GetReportModel());
    }

    private object GetReportModel()
    {
        // Load the data used by the view.
        return new { Title = "Report" };
    }
}

The important parts are the controller-owned context, the copied cookies, and the matching forms-authentication cookie name. Without the cookie, the internal request can be redirected to the login page, so the protected action breakpoint is never reached.

3. ASP.NET Core: use ViewAsPdf and ControllerContext

In ASP.NET Core, install and configure Rotativa.AspNetCore, make sure its wkhtmltopdf files are deployed, then pass the current controller context to BuildFile.

using Microsoft.AspNetCore.Mvc;
using Rotativa.AspNetCore;
using System.IO;

public class InvoicesController : Controller
{
    public IActionResult Invoice(int id)
    {
        var pdfFile = new ViewAsPdf("Invoice", new { Id = id })
        {
            FileName = $"invoice-{id}.pdf"
        };

        byte[] bytes = pdfFile.BuildFile(this.ControllerContext);
        System.IO.File.WriteAllBytes("wwwroot/output.pdf", bytes);
        return pdfFile;
    }
}

Rotativa uses wkhtmltopdf/wkhtmltoimage behind the scenes. The executable must be available to the process account, and the configured Rotativa directory must be included in the deployment.

4. Why your action breakpoint is not hit

  1. Wrong package: an ASP.NET Core controller cannot use the classic MVC ActionAsPdf API. Replace it with Rotativa.AspNetCore and ViewAsPdf.
  2. Null or incomplete context: BuildFile creates an internal HTTP-style request. A background service, static method, or manually created controller has no usable context unless you construct one explicitly. Move the call into a controller action when possible.
  3. Authentication redirect: the internal request receives no session or forms-auth cookie, reaches login instead of the target action, and renders a login or blank page. Forward cookies as shown above.
  4. Renderer failure: if wkhtmltopdf is missing, inaccessible, or blocked by permissions, the action may run but no usable PDF is produced. Check the deployed binary path and process permissions.
  5. Different URL or route: verify the action name, controller route, area, route values, and HTTP verb. A route that works in the browser may need explicit route values in the PDF result.

5. Passing route values, data, and rendering options

Keep the PDF action deterministic: load its model from route values or a service, and ensure the view can render without browser-only state.

// Classic MVC
var pdf = new ActionAsPdf("DetailsAll", "Reports", new { id = reportId })
{
    FileName = "report.pdf",
    Cookies = cookies,
    FormsAuthenticationCookieName = FormsAuthentication.FormsCookieName
};
byte[] bytes = pdf.BuildFile(ControllerContext);

Use the package’s documented custom-switch collection when the renderer needs a specific wkhtmltopdf flag (for example, disabling smart shrinking). Add switches only after confirming the rendered HTML and page dimensions are correct.

6. A repeatable diagnostic checklist

  1. Log the exact controller, action, route values, and HTTP verb used by the PDF result.
  2. Set a breakpoint at the first line of the target action and at the view.
  3. Try the target action directly in a browser while authenticated.
  4. Compare the response when cookies are present and absent; an HTML login page indicates an authentication problem.
  5. Confirm ControllerContext is non-null and belongs to the current request.
  6. Verify the Rotativa package matches the framework.
  7. Verify wkhtmltopdf/wkhtmltoimage exists in the deployed directory and is executable by the application identity.
  8. Write the returned byte array to a temporary file and inspect whether it is a valid PDF before returning it.

7. Troubleshooting common errors

Symptom Likely cause Fix
Breakpoint in target action is never reached Wrong package, missing context, route mismatch, or authentication redirect Use the framework-matching API, pass this.ControllerContext, verify route values, and forward cookies
PDF contains the login page Authentication cookie was not sent Copy Request.Cookies and set FormsAuthenticationCookieName in classic MVC
PDF is blank Blank response, failed resources, renderer error, or login redirect Save the raw bytes, inspect the generated HTML response, check renderer deployment, and test without custom switches
Null-reference or context exception BuildFile called outside a live MVC request Call it from a controller action and pass its context; otherwise construct a complete context for the hosting environment
Executable not found wkhtmltopdf files were not copied to production Deploy the Rotativa tool directory and configure its path for the process account
Styles or images missing Relative URLs cannot resolve from the renderer Use absolute, reachable URLs or configure the application so the renderer can access static assets
Timeout during rendering Slow action, external resource, or JavaScript that never settles Reduce page work, remove unreachable resources, and set a suitable renderer timeout

8. Reliability, performance, and cost considerations

  • Reliability: treat PDF generation as a second request to your application. It needs the same authentication, routing, static files, and network access as a browser request.
  • Performance: wkhtmltopdf starts a renderer and loads every referenced resource. Cache stable reports, avoid expensive database work in the view, and keep third-party requests out of the render path.
  • Concurrency: limit simultaneous renderer processes on small servers; too many parallel conversions can exhaust CPU, memory, or file descriptors.
  • Observability: log the route, elapsed time, renderer exit status, output size, and whether the response was a login page or an error page.
  • Security: do not copy arbitrary caller cookies into a URL supplied by an untrusted user. Restrict destinations and protect generated files.
  • Cost: self-hosted Rotativa costs compute and maintenance for the renderer and your application. A hosted capture API can move that operational work to a request-based service.

9. Or skip the browser setup

If you need a clean PDF or screenshot of a URL rather than a controller-specific render, ScreenshotNeo provides a single GET request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server also lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.

A capture service can remove common overlays before rendering the page.
A capture service can remove common overlays before rendering the page.

See the ScreenshotNeo API documentation for all options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', buffer);

There is a free plan with 1,000 screenshots per month and no card. Paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

10. FAQ

Can I call BuildFile from a service?

Only with a correctly constructed MVC hosting context. Prefer calling it inside a controller action, where routing, request data, and authentication are already available.

Should I use ActionAsPdf on ASP.NET Core?

No. Use the ASP.NET Core package and its ViewAsPdf API.

Why does direct navigation work while BuildFile fails?

The browser sends cookies and has a complete request context. BuildFile’s internal request does not automatically inherit those values.

Can BuildFile return bytes without writing a file?

Yes. BuildFile returns a byte array; return it from the controller or write it to storage as required.

Does ScreenshotNeo execute my controller action?

No. It captures a URL. Use Rotativa when the PDF must be produced by your MVC action and view; use ScreenshotNeo when a URL capture is sufficient.