Thiago Melo
Thiago Melo

Reputation: 1187

C# Print View to PDF

I have tried Rotativa and PdfGenerator, but it seems like they emulate a browser, or something like that.

The issue is that my view can only be saw by authenticated users.

How can I prevent not authenticated users from accessing this PDF?

An example of code I am using currently is:

    [AllowOperationsOnly]
    public ActionResult PDFReport(DateTime date)
    {
        return new Rotativa.ActionAsPdf("Report", date);
    }

    [HttpGet]
    [AllowOperationsOnly]
    public ActionResult Report(DateTime date)
    {
        // my code...
        return View();
    }

The resulting PDF is the page where users are redirected for when they are not authenticated.

Upvotes: 0

Views: 854

Answers (1)

Rion Williams
Rion Williams

Reputation: 76557

Decorate the actions that you want to only allow authenticated users to access with an [Authorize] attribute:

[AllowOperationsOnly]
[Authorize]
public ActionResult PDFReport(DateTime date)
{
    return new Rotativa.ActionAsPdf("Report", date);
}

[HttpGet]
[AllowOperationsOnly]
[Authorize]
public ActionResult Report(DateTime date)
{
    // my code...
    return View();
}

The [Authorize] attribute supports all sorts of additional overloads that allow you to define specifics such as roles or users that you want to allow access to a decorated action / controller if needed.

Regarding Rotativa

Based on this seemingly related GitHub issue, it looks like you may have to explicitly pass through any authentication tokens or cookie information to Rotativa in order for it to work as expected:

return new Rotativa.ActionAsPdf("Report")
{
        FormsAuthenticationCookieName = System.Web.Security.FormsAuthentication.FormsCookieName,
        Cookies = cookies
};

Several other resolutions also recommend trying the ViewAsPdf() method instead, which may also avoid the authentication issue (assuming you use the [Authorize] attribute to handle that within your application and then simply serve the PDF:

[AllowOperationsOnly]
public ActionResult PDFReport(DateTime date)
{
    return new Rotativa.ViewAsPdf("Report", date);
}

Upvotes: 1

Related Questions