4

I have a webapi controller action which creates an html email. currently i'm using string.format to create the html, as it's the simplest possible thing. I know this will become more complex moving forward and would like to use razor templating.

I have seen examples of how to do this for MVC controllers, but I cannot find any for how to do this within a WebApiController. Is this possible? If so do you know of any resources? My google-fu is failing me.

Jason Meckley
  • 7,589
  • 1
  • 24
  • 45
  • 1
    Have you seen this question? http://stackoverflow.com/questions/4808348/using-razor-without-mvc The answer given by Darin Dimitrov could well be your best bet. – Mark Jones Aug 02 '12 at 15:22
  • thanx @MarkJones that pointed me in the right direction. in the end I went with [RazorGenerator](http://razorgenerator.codeplex.com/). It was just a bit cleaner to implement. – Jason Meckley Aug 02 '12 at 17:24

2 Answers2

7

Checkout this article Rendering an ASP.NET MVC View to a string in a Web Api Controller by Wouter de Kort

 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)
Stefan P.
  • 9,489
  • 6
  • 29
  • 43
2

I've been using this ViewRenderer class with great success:

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

Call it like this:

var html = ViewRenderer.RenderView("~/views/emails/ActivationEmail.cshtml", emailModel);
perfect_element
  • 663
  • 9
  • 15