gpt4 book ai didi

c# - 模型中的 Rotativa PDF - ControllerContext

转载 作者:太空狗 更新时间:2023-10-30 01:17:54 27 4
gpt4 key购买 nike

我正在使用 Rotativa 从 Action / View 生成 PDF,效果很好。然而,是否可以在模型内部使用它,或者您可以纯粹在 Controller 中使用它吗?

问题是函数想要使用模型没有的 ControllerContext

var pdfResult = new ActionAsPdf("GeneratePDF", "PDF");

byte[] pdfFile = pdfResult.BuildPdf(this.ControllerContext);

我的最终结果是,如果有其他方法的话,我想要字节数组中的 PDF

最佳答案

您可以使用以下代码实例化 Controller ,然后通过该实例配置 ControllerContext - 从应用程序的任何位置。

/// <summary>
/// Creates an instance of an MVC controller from scratch
/// when no existing ControllerContext is present
/// </summary>
/// <typeparam name="T">Type of the controller to create</typeparam>
/// <returns>Controller Context for T</returns>
/// <exception cref="InvalidOperationException">thrown if HttpContext not available</exception>
public static T CreateController<T>(RouteData routeData = null)
where T : Controller, new()
{
// create a disconnected controller instance
T controller = new T();

// get context wrapper from HttpContext if available
HttpContextBase wrapper = null;
if (HttpContext.Current != null)
wrapper = new HttpContextWrapper(System.Web.HttpContext.Current);
else
throw new InvalidOperationException(
"Can't create Controller Context if no active HttpContext instance is available.");

if (routeData == null)
routeData = new RouteData();

// add the controller routing if not existing
if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller"))
routeData.Values.Add("controller", controller.GetType().Name
.ToLower()
.Replace("controller", ""));

controller.ControllerContext = new ControllerContext(wrapper, routeData, controller);
return controller;
}

这可以像这样使用:

QuotesController quotesController = ViewRenderer.CreateController<QuotesController>();
ViewAsPdf view = (ViewAsPdf)quotesController.Preview(model.Guid);
byte[] pdf = view.BuildPdf(quotesController.ControllerContext);
EmailService.Send(model, pdf);

引用:http://weblog.west-wind.com/posts/2013/Jul/15/Rendering-ASPNET-MVC-Razor-Views-outside-of-MVC-revisited

关于c# - 模型中的 Rotativa PDF - ControllerContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30024617/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com