ASP.NET Core中使用Razor視圖引擎渲染視圖爲字符串(轉)

1、視圖渲染說明html

在有些項目需求上或許須要根據模板生產靜態頁面,那麼你同樣能夠用Razor語法去直接解析你的頁面從而把解析的頁面生成靜態頁,這樣的使用場景不少,不限於生成靜態頁面,視圖引擎爲咱們提供了模型到視圖的代碼或文本生成的能力。緩存

固然在MVC 四、5的時代,咱們也使用過如RazorEngine這樣的第三方的視圖引擎,那時候MVC中的Razor與框架耦合的比較緊密,第三方開源組件幫咱們實現了在任意項目中使用Razor渲染視圖爲文本的方式;可是在.NET Core中 RazorEngine開源組件並無移植過來。框架

2、本示例,建立一個服務,用於處理將制定路徑的視圖和參數,解析成字符串async

/// <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);
}

 

使用過程:ide

1.註冊服務,在ConfigureServices() 中post

//綁定服務,
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>

返回結果;this

更多:spa

Asp.Net Core 自定義設置Http緩存處理code

ASP.NET Core -中間件(Middleware)使用

Asp.Net Core 經過自定義中間件防止圖片盜鏈的實例(轉)

相關文章
相關標籤/搜索