Ejemplo n.º 1
0
        /// <summary>
        /// 使用Razor视图引擎来生成代码文件
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="viewPath"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private string Render <TModel>(string viewPath, TModel model)
        {
            DefaultHttpContext httpContext = new DefaultHttpContext {
                RequestServices = _serviceProvider
            };
            ActionContext actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult viewResult = _viewEngine.GetView(null, viewPath, false);
            if (!viewResult.Success)
            {
                throw new InvalidOperationException($"找不到视图模板 {viewPath}");
            }

            ViewDataDictionary viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };

            using (StringWriter writer = new StringWriter())
            {
                ViewContext viewContext = new ViewContext(
                    actionContext,
                    viewResult.View,
                    viewDictionary,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    writer,
                    new HtmlHelperOptions()
                    );
                Task render = viewResult.View.RenderAsync(viewContext);
                render.Wait();
                return(writer.ToString());
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Renderiza uma view como string.
        /// </summary>
        /// <param name="viewName"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        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())
            {
                Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult 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());
            }
        }
Ejemplo n.º 3
0
        public static string ToHtml(this ViewResult result, HttpContext httpContext)
        {
            try
            {
                IRoutingFeature           feature       = httpContext.Features.Get <IRoutingFeature>();
                RouteData                 routeData     = feature.RouteData;
                string                    viewName      = result.ViewName ?? routeData.Values["action"] as string;
                ActionContext             actionContext = new ActionContext(httpContext, routeData, new ControllerActionDescriptor());
                IOptions <MvcViewOptions> options       = httpContext.RequestServices.GetRequiredService <IOptions <MvcViewOptions> >();
                Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelperOptions htmlHelperOptions = options.Value.HtmlHelperOptions;
                Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult   viewEngineResult  = result.ViewEngine?.FindView(actionContext, viewName, true) ?? options.Value.ViewEngines.Select(x => x.FindView(actionContext, viewName, true)).FirstOrDefault(x => x != null);
                Microsoft.AspNetCore.Mvc.ViewEngines.IView view = viewEngineResult.View;
                StringBuilder builder = new StringBuilder();

                using (StringWriter output = new StringWriter(builder))
                {
                    ViewContext viewContext = new ViewContext(actionContext, view, result.ViewData, result.TempData, output, htmlHelperOptions);

                    view
                    .RenderAsync(viewContext)
                    .GetAwaiter()
                    .GetResult();
                }

                return(builder.ToString());
            }
            catch
            {
                return(string.Empty);
            }
        }
Ejemplo n.º 4
0
        public async Task <string> GetTemplateHtmlAsStringAsync <T>(string viewName, T model)
        {
            var httpContext = new DefaultHttpContext()
            {
                RequestServices = _serviceProvider
            };
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            using var sw = new StringWriter();
            Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult viewResult = _razorViewEngine.FindView(actionContext, viewName, false);

            if (viewResult.View == null)
            {
                return(string.Empty);
            }

            var viewDataDictionary = new ViewDataDictionary(
                new EmptyModelMetadataProvider(),
                new ModelStateDictionary()
                )
            {
                Model = model
            };

            var viewContext = new ViewContext(
                actionContext,
                viewResult.View,
                viewDataDictionary,
                new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                sw,
                new HtmlHelperOptions()
                );

            await viewResult.View.RenderAsync(viewContext);

            return(sw.ToString());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Render partial view to string
        /// </summary>
        /// <param name="viewName">View name</param>
        /// <param name="model">Model</param>
        /// <returns>Result</returns>
        protected virtual string RenderPartialViewToString(string viewName, object model)
        {
            //get Razor view engine
            IRazorViewEngine razorViewEngine = ServiceProviderFactory.ServiceProvider.GetRequiredService <IRazorViewEngine>();

            //create action context
            ActionContext actionContext = new ActionContext(this.HttpContext, this.RouteData, this.ControllerContext.ActionDescriptor, this.ModelState);

            //set view name as action name in case if not passed
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = this.ControllerContext.ActionDescriptor.ActionName;
            }

            //set model
            ViewData.Model = model;

            //try to get a view by the name
            Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult viewResult = razorViewEngine.FindView(actionContext, viewName, false);
            if (viewResult.View == null)
            {
                //or try to get a view by the path
                viewResult = razorViewEngine.GetView(null, viewName, false);
                if (viewResult.View == null)
                {
                    throw new ArgumentNullException($"{viewName} view was not found");
                }
            }
            using (StringWriter stringWriter = new StringWriter())
            {
                ViewContext viewContext = new ViewContext(actionContext, viewResult.View, ViewData, TempData, stringWriter, new HtmlHelperOptions());

                System.Threading.Tasks.Task t = viewResult.View.RenderAsync(viewContext);
                t.Wait();
                return(stringWriter.GetStringBuilder().ToString());
            }
        }
Ejemplo n.º 6
0
        public async Task <string> RenderTemplateAsync <TViewModel>(RouteData routeData,
                                                                    string viewName, TViewModel viewModel, Dictionary <string, object> additonalViewDictionary = null, bool isMainPage = true) where TViewModel : IViewData
        {
            var httpContext = new DefaultHttpContext
            {
                RequestServices = _serviceProvider
            };

            if (viewModel.RequestPath != null)
            {
                httpContext.Request.Host     = HostString.FromUriComponent(viewModel.RequestPath.Host);
                httpContext.Request.Scheme   = viewModel.RequestPath.Scheme;
                httpContext.Request.PathBase = PathString.FromUriComponent(viewModel.RequestPath.PathBase);

                _logger.LogDebug($"RequestPath != null");
                _logger.LogTrace($"\tHost: {viewModel.RequestPath.Host} -> {httpContext.Request.Host}");
                _logger.LogTrace($"\tScheme: {viewModel.RequestPath.Scheme}");
                _logger.LogTrace($"\tPathBase: {viewModel.RequestPath.PathBase} -> {httpContext.Request.PathBase}");
            }

            var actionDescriptor = new ActionDescriptor
            {
                RouteValues = routeData.Values.ToDictionary(kv => kv.Key, kv => kv.Value.ToString())
            };
            var actionContext = new ActionContext(httpContext, routeData, actionDescriptor);

            using (var outputWriter = new StringWriter())
            {
                Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult viewResult = null;
                if (IsApplicationRelativePath(viewName) || IsRelativePath(viewName))
                {
                    _logger.LogDebug($"Relative path");
#if NETSTANDARD2_0
                    viewResult = _viewEngine.GetView(_hostingEnvironment.WebRootPath, viewName, isMainPage);
#else
                    if (_hostingEnvironment is Microsoft.AspNetCore.Hosting.IWebHostEnvironment webHostEnvironment)
                    {
                        _logger.LogDebug($"_hostingEnvironment is IWebHostEnvironment -> GetView from WebRootPath: {webHostEnvironment.WebRootPath}");
                        viewResult = _viewEngine.GetView(webHostEnvironment.WebRootPath, viewName, isMainPage);
                    }
                    else
                    {
                        _logger.LogDebug($"_hostingEnvironment is IHostEnvironment -> GetView from ContentRootPath: {_hostingEnvironment.ContentRootPath}");
                        viewResult = _viewEngine.GetView(_hostingEnvironment.ContentRootPath, viewName, isMainPage);
                    }
#endif
                }
                else
                {
                    _logger.LogDebug($"Not a relative path");
                    viewResult = _viewEngine.FindView(actionContext, viewName, isMainPage);
                }


                var viewDictionary = new ViewDataDictionary <TViewModel>(viewModel.ViewData, viewModel);
                if (additonalViewDictionary != null)
                {
                    _logger.LogDebug($"additonalViewDictionary count: {additonalViewDictionary.Count}");
                    foreach (var kv in additonalViewDictionary)
                    {
                        if (!viewDictionary.ContainsKey(kv.Key))
                        {
                            viewDictionary.Add(kv);
                        }
                        else
                        {
                            viewDictionary[kv.Key] = kv.Value;
                        }
                    }
                }

                var tempDataDictionary = new TempDataDictionary(httpContext, _tempDataProvider);

                if (!viewResult.Success)
                {
                    _logger.LogError($"Failed to render template {viewName} because it was not found. \r\nThe following locations are searched: \r\n{string.Join("\r\n", viewResult.SearchedLocations) }");
                    throw new TemplateServiceException($"Failed to render template {viewName} because it was not found. \r\nThe following locations are searched: \r\n{string.Join("\r\n", viewResult.SearchedLocations) }");
                }

                try
                {
                    var viewContext = new ViewContext(actionContext, viewResult.View, viewDictionary,
                                                      tempDataDictionary, outputWriter, new HtmlHelperOptions());

                    await viewResult.View.RenderAsync(viewContext);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Failed to render template due to a razor engine failure");
                    throw new TemplateServiceException("Failed to render template due to a razor engine failure", ex);
                }

                await outputWriter.FlushAsync();

                return(outputWriter.ToString());
            }
        }