我終於有辦法做到這一點。
其實rotativa的方法「返回新的ViewAsPdf(模型)」返回HttpResponseStream。我們幾乎無法做的事情。但是,我們可以通過使用自定義屬性來修改/更改響應。我們可以覆蓋操作過濾器的OnResultExecuted()方法。
控制器的動作
[HttpGet]
[ActionDownload] //here a custom action filter added
public ActionResult DownloadDocument()
{
var htmlContent = "<h1>sachin Kumar</hi>";
var model = new PdfInfo {FtContent = htmlContent, FtName = "Populate Form"};
return new ViewAsPdf(model);
}
自定義操作過濾器:
public class ActionDownloadAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
//Add content-disposition header to response so that browser understand to download as an attachment.
filterContext.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + "Report.pdf");
base.OnResultExecuted(filterContext);
}
}
爲什麼這不是被接受的答案?這很簡單,幾乎不需要任何額外的代碼,並且工作得很好。 – Simon