美文网首页
Razor To Html

Razor To Html

作者: 晒雨LL | 来源:发表于2022-01-18 16:53 被阅读0次

    ActionFilterAttribute.OnResultExecutionAsync

    protected async Task<string> 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<IRazorViewEngine>();
        ITempDataProvider tempDataProvider = serviceProvider.GetService<ITempDataProvider>();
    
        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

          本文链接:https://www.haomeiwen.com/subject/jzwkhrtx.html