Is there a way to process an MVC view (aspx file) from a non-web application?

后端 未结 5 1277
执念已碎
执念已碎 2020-12-14 23:55

I have a background service running which sends out emails to users of my website. I would like to write the email templates as MVC views, to keep things consistent (so tha

5条回答
  •  时光说笑
    2020-12-15 00:33

    Ended up answering my own question :)

    public class AspHost : MarshalByRefObject
    {
        public string _VirtualDir;
        public string _PhysicalDir;
    
        public string ViewToString(string aspx, Dictionary viewData, T model)
        {
            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                using (HtmlTextWriter tw = new HtmlTextWriter(sw))
                {
                    var workerRequest = new SimpleWorkerRequest(aspx, "", tw);
                    HttpContext.Current = new HttpContext(workerRequest);
    
                    ViewDataDictionary viewDataDictionary = new ViewDataDictionary(model);
                    foreach (KeyValuePair pair in viewData)
                    {
                        viewDataDictionary.Add(pair.Key, pair.Value);
                    }
    
                    object view = BuildManager.CreateInstanceFromVirtualPath(aspx, typeof(object));
    
                    ViewPage viewPage = view as ViewPage;
                    if (viewPage != null)
                    {
                        viewPage.ViewData = viewDataDictionary;
                    }
                    else
                    {
                        ViewUserControl viewUserControl = view as ViewUserControl;
                        if (viewUserControl != null)
                        {
                            viewPage = new ViewPage();
                            viewPage.Controls.Add(viewUserControl);
                        }
                    }
    
                    if (viewPage != null)
                    {
                        HttpContext.Current.Server.Execute(viewPage, tw, true);
    
                        return sb.ToString();
                    }
    
                    throw new InvalidOperationException();
                }
            }
        }
    
        public static AspHost SetupFakeHttpContext(string physicalDir, string virtualDir)
        {
            return (AspHost)ApplicationHost.CreateApplicationHost(
                typeof(AspHost), virtualDir, physicalDir);
        }
    }
    

    Then, to render a file:

    var host = AspHost.SetupFakeHttpContext("Path/To/Your/MvcApplication", "/");
    var viewData = new ViewDataDictionary(){ Model = myModel };
    String rendered = host.ViewToString("~/Views/MyView.aspx", new Dictionary(viewData), viewData.Model);
    

提交回复
热议问题