Razor To Html

ActionFilterAttribute.OnResultExecutionAsync

protected async Task RenderToStringAsync(ResultExecutingContext context)
{
    string viewName = "";
    ViewDataDictionary viewDictionary = null;
    if (context.Result is ViewResult result)
    {
        viewName = result.ViewName;
        viewName = string.IsNullOrWhiteSpace(viewName) ? context.RouteData.Values["action"].ToString() : viewName;
        viewDictionary = result.ViewData;
    }
    IServiceProvider serviceProvider = context.HttpContext.RequestServices;
    IRazorViewEngine razorViewEngine = serviceProvider.GetService();
    ITempDataProvider tempDataProvider = serviceProvider.GetService();

    var actionContext = context;

    //var httpContext = new DefaultHttpContext { RequestServices = serviceProvider };
    //new新对象viewResult.View.RenderAsync会报错Could not find an IRouter associated with the ActionContext.
    //var actionContext =  new ActionContext(httpContext, context.RouteData, new ActionDescriptor());

    using (var stringWriter = new StringWriter())
    {
        var viewResult = razorViewEngine.FindView(actionContext, viewName, true);
        if (viewResult.View == null)
            throw new ArgumentNullException($"未找到视图: {viewName}");

        var viewContext = new ViewContext(
            actionContext,
            viewResult.View,
            viewDictionary,
            new TempDataDictionary(actionContext.HttpContext, tempDataProvider),
            stringWriter,
            new HtmlHelperOptions());

        await viewResult.View.RenderAsync(viewContext);
        return stringWriter.ToString();
    }
}

你可能感兴趣的:(Razor To Html)