ASP.NET Core 中,可能需要从一个后台方法(比如在控制器中)解析一个视图(View)并获取生成的 HTML 字符串。这在一些场景下很有用,比如生成电子邮件内容或者进行动态内容渲染。本文主要分享一下,在ASP.NET Core MVC项目中后台获取视图解析后的html字符串的代码。

1、添加将视图(View)生成html字符串的扩展方法

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.IO;
using System.Threading.Tasks;
namespace CC.Web.Helpers
{
    public static class ControllerExtensions
    {
        public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }
            controller.ViewData.Model = model;
            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
                if (viewResult.Success == false)
                {
                    return $"A view with the name {viewName} could not be found";
                }
                ViewContext viewContext = new ViewContext(
                    controller.ControllerContext,
                    viewResult.View,
                    controller.ViewData,
                    controller.TempData,
                    writer,
                    new HtmlHelperOptions()
                );
                await viewResult.View.RenderAsync(viewContext);
                return writer.GetStringBuilder().ToString();
            }
        }
    }
}

2、上面RenderViewAsync扩展方法的使用方法

1)对于View视图使用代码

viewHtml = await this.RenderViewAsync("Report", model);

2)对于PartialView视图使用代码

partialViewHtml = await this.RenderViewAsync("Report", model, true);

推荐文档