WebApi中利用Razor模板引擎来生成html

在服器端基于Razor来生成html的一个思路

using System.Web.Mvc;

using System.IO;

using System.Web.Routing;

using System.Web;   

public class MailTemplateController : ControllerBase

    {

        protected override void ExecuteCore() { }

        public static string RenderViewToString(string viewName, object viewData)

        {

            using (var writer = new StringWriter())

            {

                var routeData = new RouteData();

                routeData.Values.Add("controller", "DummyController");

                var fakeControllerContext = new ControllerContext(new HttpContextWrapper(

                    new HttpContext(new HttpRequest(null, "http://dummy.com", null),

                        new HttpResponse(null))), routeData, new MailTemplateController());

                var razorViewEngine = new RazorViewEngine();

                var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);

   

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

                razorViewResult.View.Render(viewContext, writer);

                return writer.ToString();

            }

        }

    }

RenderViewToString("~/Views/Home/Index.cshtml", new MailModel());

注意Views所在目录下需要有一个Web.config文件

RazorRazor语法参考:https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor

灵感之源:

http://stackoverflow.com/questions/23494741/mvc-5-render-view-to-string

https://forums.asp.net/t/2017674.aspx?How+to+return+rendered+razor+view+from+Web+API+controller

posted @ 2017-03-13 10:46  队长  阅读(948)  评论(0编辑  收藏