webapi将模型渲染为控制器内的html

时间:2012-08-02 14:19:55

标签: razor asp.net-web-api

我有一个webapi控制器操作,可以创建一个html电子邮件。目前我正在使用string.format来创建html,因为这是最简单的事情。我知道这将变得更加复杂,并希望使用剃刀模板。

我已经看到了如何为MVC控制器执行此操作的示例,但我找不到如何在WebApiController内执行此操作。这可能吗?如果是这样,你知道任何资源吗?我的google-fu让我失望。

2 个答案:

答案 0 :(得分:7)

Wouter de Kort查看本文Rendering an ASP.NET MVC View to a string in a Web Api Controller

 public static string RenderViewToString(string controllerName, string viewName, 
                                         object viewData)
{
    HttpContextBase contextBase = new HttpContextWrapper(HttpContext.Current);

    var routeData = new RouteData();
    routeData.Values.Add("controller", controllerName);
    var controllerContext = new ControllerContext(contextBase, routeData, 
                                                   new EmptyController());

    var razorViewEngine = new RazorViewEngine();
    var razorViewResult = razorViewEngine.FindView(controllerContext, viewName, 
                                                     "", false);

    var writer = new StringWriter();
    var viewContext = new ViewContext(controllerContext, razorViewResult.View, 
           new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
    razorViewResult.View.Render(viewContext, writer);

    return writer.ToString();
}

private class EmptyController : ControllerBase
{
    protected override void ExecuteCore() { }
}

//You can simply call this from anywhere in your Web Api Controller: 

RenderViewToString("controller", "view", model)

答案 1 :(得分:2)

我一直在使用这个ViewRenderer类取得了巨大的成功:

https://github.com/RickStrahl/WestwindToolkit/blob/master/Westwind.Web.Mvc/Utils/ViewRenderer.cs

这样称呼:

var html = ViewRenderer.RenderView("~/views/emails/ActivationEmail.cshtml", emailModel);