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.
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With