一、视图渲染说明
在有些项目需求上或许需要根据模板生产静态页面,那么你一样可以用Razor语法去直接解析你的页面从而把解析的页面生成静态页,这样的使用场景很多,不限于生成静态页面,视图引擎为我们提供了模型到视图的代码或文本生成的能力。
当然在MVC 4、5的时代,我们也使用过如RazorEngine这样的第三方的视图引擎,那时候MVC中的Razor与框架耦合的比较紧密,第三方开源组件帮我们实现了在任意项目中使用Razor渲染视图为文本的方式;但是在.NET Core中 RazorEngine开源组件并没有移植过来。
二、本示例,创建一个服务,用于处理将制定路径的视图和参数,解析成字符串
/// <summary> /// 定义视图渲染服务 /// </summary> public class ViewRenderService : IViewRenderService { private readonly IRazorViewEngine _razorViewEngine; private readonly ITempDataProvider _tempDataProvider; private readonly IServiceProvider _serviceProvider; public ViewRenderService(IRazorViewEngine razorViewEngine, ITempDataProvider tempDataProvider, IServiceProvider serviceProvider) { _razorViewEngine = razorViewEngine; _tempDataProvider = tempDataProvider; _serviceProvider = serviceProvider; } public async Task<string> RenderToStringAsync(string viewName, object model) { var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); using (var sw = new StringWriter()) { var viewResult = _razorViewEngine.FindView(actionContext, viewName, false); if (viewResult.View == null) { throw new ArgumentNullException($"{viewName} does not match any available view"); } var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; var viewContext = new ViewContext( actionContext, viewResult.View, viewDictionary, new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), sw, new HtmlHelperOptions() ); await viewResult.View.RenderAsync(viewContext); return sw.ToString(); } } } public interface IViewRenderService { Task<string> RenderToStringAsync(string viewName, object model); }
使用过程:
1.注册服务,在ConfigureServices() 中
//绑定服务, services.AddScoped<IViewRenderService, ViewRenderService>();
2.在控制器中通过服务调用方法
public class Emall1MvcController : Controller { private IViewRenderService _view = null; public Emall1MvcController(IViewRenderService view) { this._view= view; } public IActionResult Index() { return View(123); } //调用服务方法,返回html 字符串 public async Task<string> Test1() { return await _view.RenderToStringAsync("Emall1Mvc/Index", 456); } }
@model int @{ ViewData["Title"] = "Index"; } <h2>Index</h2> 测试变量如下: <p> @Model </p>
返回结果;
更多: