Asp.net-Mvc-5

為什麼 Rotativa 總是生成我的登錄頁面?為什麼慢?

  • November 8, 2020

我正在使用這個 Rotativa 1.6.4 程式碼範例從我的 .NET MVC 5 應用程序中的頁面生成 PDF。

public ActionResult PrintIndex()
{
   var a = new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
   a.Cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k].Value);
   a.FormsAuthenticationCookieName = System.Web.Security.FormsAuthentication.FormsCookieName;
   a.CustomSwitches = "--load-error-handling ignore";
   return a;
}

public ActionResult Index(string name)
{
   ViewBag.Message = string.Format("Hello {0} to ASP.NET MVC!", name);

   return View();
}

它不是在列印索引頁面,而是在列印我的登錄頁面。

一旦我解決了身份驗證問題,即使使用CustomSwitches. (幾分鐘)

上面的程式碼實際上可能對您有用 - 它使用該屬性解決了身份驗證問題Cookies,但對我來說太慢了。

如何快速列印安全頁面?

我為此苦苦掙扎了大約 8 個小時,我發布自己的解決方案部分是作為自我參考,但也因為堆棧溢出沒有好的答案。

下載 Rotativa 原始碼

它在 github 上是開源的。我嘗試了許多人們說要使用的UrlAsPdf其他解決方案以及來自 github 問題的其他解決方案,但這些都不適合我。除了閱讀程式碼之外的另一個優點……建構pdb文件,將其放入您的解決方案並對其進行調試。它會透露很多!我發現的一件事是 Rotativawkhtmltopdf.exe在幕後使用。這使用 web 工具包來呈現 html。此外,該命令通常會向 url 發出 http 請求。為什麼?我們已經在伺服器上了!這意味著我們必須重新進行身份驗證並解釋為什麼我們有時可以獲取登錄頁面。複製 cookie 會有所幫助,但既然可以線上進行,為什麼還要向自己發出 http 請求呢?

突破

我在原始碼中找到了一個擴展方法,GetHtmlFromView它生成視圖 html 而無需單獨的 http 請求!是的!誰打電話GetHtmlFromView?為什麼ViewAsPdf當然。所以這導致我嘗試下面的程式碼,它可以工作而且速度很快!

放入 ASP.NET MVC 控制器操作的程式碼:

// ViewAsPdf calls Rotativa.Extensions.ControllerContextExtensions.GetHtmlFromView
// Which generates the HTML inline instead of making a separate http request which CallDriver (wkhtmltopdf.exe) does.
var a = new ViewAsPdf();
a.ViewName = "Index";
a.Model = _service.GetMyViewModel(id);
var pdfBytes = a.BuildPdf(ControllerContext);

// Optionally save the PDF to server in a proper IIS location.
var fileName = string.Format("my_file_{0}.pdf", id);
var path = Server.MapPath("~/App_Data/" + fileName);
System.IO.File.WriteAllBytes(path, pdfBytes);

// return ActionResult
MemoryStream ms = new MemoryStream(pdfBytes);
return new FileStreamResult(ms, "application/pdf");

引用自:https://stackoverflow.com/questions/35067191