MVC5 在基本控制器上实现自定义 FileResult 函数 class

MVC5 Implementing Custom FileResult function on Base Controller class

我对 MVC 比较陌生,所以如果我从错误的角度解决这个问题,请告诉我。

我有几种观点想以 html 和 pdf 格式提供给用户。使用 HiQPdf dll,这是一项非常简单的任务,所以我只是想在我的 Controller base class 上包装一个辅助函数,这样我就可以做类似的事情:

public ActionResult MyAction(MyActionVM model) {

  if(Request.QueryString["type"] == "pdf") {
    return Pdf("ViewName", model, "htmlaspdf.pdf");
  }

  return View("ViewName");
}

这是我目前已经实现的,它编译得很好,在我天真的自我看来它应该可以工作。然而,当我 运行 操作时,它在 Pdf() 函数的第一行失败,下面的例外对我来说没有多大意义。它显然是在调用 ViewContext ctor,但我不确定 为什么 或如何修复它。有什么见解吗?

public class CustomBaseController : Controller {
  protected FileResult Pdf(string viewname, object data, string filename) {
    HtmlToPdf converter = new HtmlToPdf(); //Exception stack references this line
    MemoryStream ms = new MemoryStream();

    using (var sw = new StringWriter()) {
      ViewResult view;
      if (String.IsNullOrWhiteSpace(viewname))
        view = this.View(data);
      else
        view = this.View(viewname, data);

      //roughly taken from the examples here: http://blog.janjonas.net/2011-06-18/aspnet-mvc3-controller-extension-method-render-partial-view-string
      var viewContext = new ViewContext(this.ControllerContext, view.View, ViewData, TempData, sw);
      view.View.Render(viewContext, sw);
      converter.ConvertHtmlToStream(sw.GetStringBuilder().ToString(), null, ms);
    }

    ms.Position = 0;

    return File(ms, "application/octet-stream", filename);
  }
}

异常

[ArgumentNullException: Value cannot be null.
Parameter name: view]
   System.Web.Mvc.ViewContext..ctor(ControllerContext controllerContext, IView view, ViewDataDictionary viewData, TempDataDictionary tempData, TextWriter writer) +326
   MyNamespace.Utilities.MyNamespaceController.Pdf(String viewname, Object data, String filename) in G:\brendans\Projects\MyNamespace\MyNamespace\Utilities\MyNamespaceController.cs:21

感谢丹尼尔J.G。这种细微的修改非常有效。

  MemoryStream ms = new MemoryStream();
  HtmlToPdf converter = new HtmlToPdf();

  ViewData.Model = model;

  using (var sw = new StringWriter()) {
    var viewengineresult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewname);
    var viewcontext = new ViewContext(this.ControllerContext, viewengineresult.View, ViewData, TempData, sw);
    viewengineresult.View.Render(viewcontext, sw);
    converter.ConvertHtmlToStream(sw.GetStringBuilder().ToString(), null, ms);
  }

  ms.Position = 0;

  return File(ms, "application/octet-stream", filename);