Example #1
0
        protected async Task <string> RenderPartialViewToString(ICompositeViewEngine viewEngine, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = ControllerContext.ActionDescriptor.ActionName;
            }

            ViewData.Model = model;

            using (var writer = new StringWriter())
            {
                string           path       = (new Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
                ViewEngineResult viewResult =
                    viewEngine.GetView(path, viewName, false);

                ViewContext viewContext = new ViewContext(
                    ControllerContext,
                    viewResult.View,
                    ViewData,
                    TempData,
                    writer,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(writer.GetStringBuilder().ToString());
            }
        }
        private void ExecuteTemplateRendering(TextWriter sw, IPublishedRequest request)
        {
            var httpContext = _httpContextAccessor.GetRequiredHttpContext();

            // isMainPage is set to true here to ensure ViewStart(s) found in the view hierarchy are rendered
            var viewResult = _viewEngine.GetView(null, $"~/Views/{request.GetTemplateAlias()}.cshtml", isMainPage: true);

            if (viewResult.Success == false)
            {
                throw new InvalidOperationException($"A view with the name {request.GetTemplateAlias()} could not be found");
            }

            var viewData = new ViewDataDictionary(_modelMetadataProvider, new ModelStateDictionary())
            {
                Model = request.PublishedContent
            };

            var writer      = new StringWriter();
            var viewContext = new ViewContext(
                new ActionContext(httpContext, httpContext.GetRouteData(), new ControllerActionDescriptor()),
                viewResult.View,
                viewData,
                _tempDataDictionaryFactory.GetTempData(httpContext),
                writer,
                new HtmlHelperOptions()
                );


            viewResult.View.RenderAsync(viewContext).GetAwaiter().GetResult();

            var output = writer.GetStringBuilder().ToString();

            sw.Write(output);
        }
        public async Task <bool> RenderAsync(string name, object model, IOwinEnvironment context, CancellationToken cancellationToken)
        {
            var httpContext = context.Request[MicrosoftHttpContextKey] as HttpContext;

            if (httpContext == null)
            {
                _logger.Error($"Request dictionary does not contain '{MicrosoftHttpContextKey}'", nameof(RazorViewRenderer));
                return(false);
            }

            // TODO ideally this would be done by the existing middleware pipeline
            // if authentication and view rendering were split up
            GetUserIdentity(httpContext, _logger);

            var actionContext = GetActionContext(httpContext);

            ViewEngineResult viewEngineResult;

            if (IsApplicationRelativePath(name))
            {
                var basePath = Directory.GetCurrentDirectory();
                _logger.Trace($"Getting view '{name}' relative to '{basePath}'");
                viewEngineResult = _viewEngine.GetView(basePath, name, true);
            }
            else
            {
                viewEngineResult = _viewEngine.FindView(actionContext, name, true);
            }

            if (!viewEngineResult.Success)
            {
                _logger.Trace($"Could not find Razor view '{name}'", nameof(RazorViewRenderer));
                return(false);
            }

            var view = viewEngineResult.View;

            using (var writer = new StreamWriter(context.Response.Body))
            {
                var viewDataDictionary = new ViewDataDictionary(
                    new EmptyModelMetadataProvider(),
                    new ModelStateDictionary())
                {
                    Model = model
                };

                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewDataDictionary,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    writer,
                    new HtmlHelperOptions());

                cancellationToken.ThrowIfCancellationRequested();
                await view.RenderAsync(viewContext);

                return(true);
            }
        }
Example #4
0
        public async Task <string> RenderViewAsync <TModel>(Controller controller, string viewName, TModel model, bool isPartial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }

            controller.ViewData.Model = model;

            using (var writer = new StringWriter())
            {
                var viewResult = _compositeViewEngine.GetView(_hostingEnvironment.ContentRootPath, viewName, !isPartial);

                if (viewResult.Success == false)
                {
                    _logger.LogError($"A view with the name {viewName} could not be found");
                    throw new Exception();
                }

                var viewContext = new ViewContext(
                    controller.ControllerContext,
                    viewResult.View,
                    controller.ViewData,
                    controller.TempData,
                    writer,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(writer.GetStringBuilder().ToString());
            }
        }
        public static async Task <string> RenderView(string path, ViewDataDictionary viewDataDictionary)
        {
            if (ServiceProvider == null)
            {
                throw new InvalidOperationException($"In order to use the facade, {nameof(UseMailTemplates)} must be called in Startup.Configure method. ");
            }

            path = path ?? throw new ArgumentNullException(nameof(path));
            viewDataDictionary = viewDataDictionary ?? throw new ArgumentNullException(nameof(viewDataDictionary));

            path = path.EndsWith(".cshtml") ? path : $"{path}.cshtml";
            path = path.Trim('/');

            using (IServiceScope scope = ServiceProvider.CreateScope())
            {
                MailOptions          options             = scope.ServiceProvider.GetRequiredService <IOptions <MailOptions> >().Value;
                ICompositeViewEngine viewEngine          = scope.ServiceProvider.GetRequiredService <ICompositeViewEngine>();
                ITempDataProvider    tempDataProvider    = scope.ServiceProvider.GetRequiredService <ITempDataProvider>();
                IHttpContextAccessor httpContextAccessor = scope.ServiceProvider.GetRequiredService <IHttpContextAccessor>();
                HttpContext          httpContext         = httpContextAccessor.HttpContext;
                if (httpContext == null)
                {
                    httpContext = new DefaultHttpContext
                    {
                        RequestServices = scope.ServiceProvider
                    };
                }
                ActionContext actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
                viewDataDictionary.Model = null;

                using (StringWriter sw = new StringWriter())
                {
                    ViewEngineResult viewResult = viewEngine.GetView($"{options.ViewTemplateBasePath}/{path}", $"{options.ViewTemplateBasePath}/{path}", true);

                    if (viewResult?.View == null)
                    {
                        throw new Exception($"View {options.ViewTemplateBasePath}/{path} not found.");
                    }

                    ViewContext viewContext = new ViewContext(actionContext, viewResult.View, viewDataDictionary, new TempDataDictionary(httpContext, tempDataProvider), sw, new HtmlHelperOptions());

                    await viewResult.View.RenderAsync(viewContext);

                    sw.Flush();

                    if (viewContext.ViewData != viewDataDictionary)
                    {
                        var keys = viewContext.ViewData.Keys.ToArray();
                        foreach (var key in keys)
                        {
                            viewDataDictionary[key] = viewContext.ViewData[key];
                        }
                    }

                    return(sw.ToString());
                }
            }
        }
Example #6
0
        List <PackageListItem> Widgets()
        {
            var widgets = new List <PackageListItem>();

            foreach (var assembly in Configuration.GetAssemblies())
            {
                var name = assembly.GetName().Name;

                if (name != "Blogifier.Core")
                {
                    var path = $"~/Views/Shared/Components/{name}/Settings.cshtml";
                    var view = _engine.GetView("", path, false);

                    var item = new PackageListItem
                    {
                        Title       = name,
                        Description = name,
                        Version     = assembly.GetName().Version.ToString(),
                        LastUpdated = System.IO.File.GetLastWriteTime(assembly.Location)
                    };

                    try
                    {
                        Type t = assembly.GetType("PackageInfo");
                        if (t != null)
                        {
                            var info       = (IPackageInfo)Activator.CreateInstance(t);
                            var attributes = info.GetAttributes();
                            if (attributes != null)
                            {
                                item.Author         = string.IsNullOrEmpty(attributes.Author) ? "Unknown" : attributes.Author;
                                item.Cover          = string.IsNullOrEmpty(attributes.Cover) ? BlogSettings.Cover : attributes.Cover;
                                item.Description    = attributes.Description;
                                item.Icon           = string.IsNullOrEmpty(attributes.Icon) ? BlogSettings.Logo : attributes.Icon;
                                item.ProjectUrl     = attributes.ProjectUrl;
                                item.Tags           = attributes.Tags;
                                item.Title          = attributes.Title;
                                item.ControllerName = attributes.ControllerName;
                            }
                        }
                    }
                    catch { }

                    var disabled = Disabled();
                    //var maxLen = 70;

                    //item.Description = item.Description.Length > maxLen ? item.Description.Substring(0, maxLen) + "..." : item.Description;
                    item.HasSettings = view.Success;
                    item.Enabled     = disabled == null || !disabled.Contains(name);
                    widgets.Add(item);
                }
            }
            return(widgets);
        }
Example #7
0
        protected virtual async Task RenderPartialCoreAsync(
            string partialViewName,
            object model,
            ViewDataDictionary viewData,
            TextWriter writer)
        {
            if (partialViewName == null)
            {
                throw new ArgumentNullException(nameof(partialViewName));
            }

            var viewEngineResult = _viewEngine.GetView(
                ViewContext.ExecutingFilePath,
                partialViewName,
                isMainPage: false);
            var originalLocations = viewEngineResult.SearchedLocations;

            if (!viewEngineResult.Success)
            {
                viewEngineResult = _viewEngine.FindView(ViewContext, partialViewName, isMainPage: false);
            }

            if (!viewEngineResult.Success)
            {
                var locations = string.Empty;
                if (originalLocations.Any())
                {
                    locations = Environment.NewLine + string.Join(Environment.NewLine, originalLocations);
                }

                if (viewEngineResult.SearchedLocations.Any())
                {
                    locations +=
                        Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations);
                }

                throw new InvalidOperationException(
                          Resources.FormatViewEngine_PartialViewNotFound(partialViewName, locations));
            }

            var view = viewEngineResult.View;

            using (view as IDisposable)
            {
                // Determine which ViewData we should use to construct a new ViewData
                var baseViewData = viewData ?? ViewData;

                var newViewData = new ViewDataDictionary <object>(baseViewData, model);
                var viewContext = new ViewContext(ViewContext, view, newViewData, writer);

                await viewEngineResult.View.RenderAsync(viewContext);
            }
        }
Example #8
0
        public async Task <string> RenderToStringAsync(Controller controller, string viewName, object model)
        {
            using (var sw = new StringWriter())
            {
                var viewResult = _viewEngine.GetView(viewName, viewName, false);
                if (!viewResult.Success)
                {
                    viewResult = _viewEngine.FindView(controller.ControllerContext, viewName, false);
                }

                //if (!viewResult.Success)
                //{
                //    var endPointDisplay = controller.HttpContext.Request.GetEndpoint().DisplayName;

                //    if (endPointDisplay.Contains(".Areas."))
                //    {
                //        //search in Areas
                //        var areaName = endPointDisplay.Substring(endPointDisplay.IndexOf(".Areas.") + ".Areas.".Length);
                //        areaName = areaName.Substring(0, areaName.IndexOf(".Controllers."));

                //        var viewNamePath = $"~/Areas/{areaName}/views/{controller.HttpContext.Request.RouteValues["controller"]}/{controller.HttpContext.Request.RouteValues["action"]}.cshtml";

                //        viewResult = viewEngine.GetView(viewNamePath, viewNamePath, false);
                //    }

                //    if (!viewResult.Success)
                //        throw new Exception($"A view with the name '{viewNamePath}' could not be found");
                //}

                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(
                    controller.ControllerContext,
                    viewResult.View,
                    controller.ViewData,
                    controller.TempData,
                    sw,
                    new HtmlHelperOptions()
                    );

                await viewResult.View.RenderAsync(viewContext);

                return(sw.ToString());
            }
        }
        private async Task HandleMvcException(HttpContext context, HttpException ex)
        {
            var viewModel = new ErrorViewModel
            {
                StatusCode   = ex.StatusCode,
                ErrorMessage = ex.Message
            };
            var viewResult = viewEngine.GetView("~/", "~/Views/Shared/Error.cshtml", true);

            if (viewResult.Success)
            {
                //创建临时的StringWriter实例,用来配置到视图上下文中
                using (var output = new StringWriter())
                {
                    //视图上下文对于视图渲染来说很重要,视图中的前后台交互都需要它
                    var viewContext = new ViewContext()
                    {
                        HttpContext = context,
                        Writer      = output,
                        RouteData   = new Microsoft.AspNetCore.Routing.RouteData()
                        {
                        },
                        ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                        {
                            Model = viewModel
                        },
                        TempData         = new TempDataDictionary(context, tempDataProvider), //ViewData
                        View             = viewResult.View,
                        FormContext      = new FormContext(),
                        ActionDescriptor = new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor()
                    };
                    //渲染
                    try
                    {
                        await viewResult.View.RenderAsync(viewContext);
                    }
                    catch (Exception e)
                    {
                        var msg = e.Message;
                    }

                    var html = output.ToString();
                    context.Response.ContentType = "text/html";
                    //输出到响应体
                    await context.Response.WriteAsync(html);
                }
            }
            else
            {
                await context.Response.WriteAsync(JsonSerializer.Serialize(viewModel, jsonOptions.JsonSerializerOptions).ToString());
            }
        }
Example #10
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = null;
            ViewEngineResult result = _viewEngine.GetView(string.Empty, $"/{PartialId}", isMainPage: false);
            var viewBuffer          = new ViewBuffer(_viewBufferScope, result.ViewName, ViewBuffer.PartialViewPageSize);

            using (var writer = new ViewBufferTextWriter(viewBuffer, Encoding.UTF8))
            {
                await RenderPartialViewAsync(writer, GetViewModel(), result.View);

                output.Content.SetHtmlContent(viewBuffer);
            }
        }
Example #11
0
        public async Task <IViewComponentResult> InvokeAsync(string templateName, string language)
        {
            var defaultViewPath   = $"~/{templateName}.cshtml";
            var localizedViewPath = $"~/{templateName}.{language}.cshtml";

            var view = _compositeViewEngine.GetView(null, localizedViewPath, false);

            if (view != null && view.Success)
            {
                return(View(localizedViewPath));
            }

            return(View(defaultViewPath));
        }
Example #12
0
        public IActionResult Packages(string packageType = "Widgets")
        {
            var type  = packageType.ToLower();
            var model = new AdminPackagesModel {
                Profile = GetProfile()
            };

            model.Packages = new List <PackageListItem>();

            if (type == "widgets")
            {
                foreach (var assembly in Configuration.GetAssemblies())
                {
                    var name = assembly.GetName().Name;

                    if (name != "Blogifier.Core")
                    {
                        var path = $"~/Views/Shared/Components/{name}/Settings.cshtml";
                        var view = _engine.GetView("", path, false);

                        var item = new PackageListItem
                        {
                            Title       = name,
                            Description = name,
                            Version     = assembly.GetName().Version.ToString()
                        };

                        try
                        {
                            Type t = assembly.GetType("PackageInfo");
                            if (t != null)
                            {
                                var info = (IPackageInfo)Activator.CreateInstance(t);
                                item = info.GetAttributes();
                            }
                        }
                        catch { }

                        var disabled = Disabled();

                        item.Description = item.Description.Length > 50 ? item.Description.Substring(0, 50) + "..." : item.Description;
                        item.HasSettings = view.Success;
                        item.Enabled     = disabled == null || !disabled.Contains(name);
                        model.Packages.Add(item);
                    }
                }
            }

            return(View($"{_theme}Packages/Widgets.cshtml", model));
        }
Example #13
0
        public IActionResult Error(int code)
        {
            SetViewBag();

            var viewName = $"~/Views/Themes/{AppSettings.Theme}/Error.cshtml";
            var result   = _viewEngine.GetView("", viewName, false);

            if (result.Success)
            {
                return(View(viewName, code));
            }
            else
            {
                return(View("~/Views/Shared/_Error.cshtml", code));
            }
        }
Example #14
0
        private async Task <string> CreateDataNode(string originalHtml, HttpContext context)
        {
            var html       = string.Empty;
            var viewResult = _viewEngine.GetView("~/", "~/Views/Shared/_ToolLayout.cshtml", true);

            if (viewResult.Success)
            {
                //创建临时的StringWriter实例,用来配置到视图上下文中
                using (var output = new StringWriter())
                {
                    //视图上下文对于视图渲染来说很重要,视图中的前后台交互都需要它
                    var viewContext = new ViewContext()
                    {
                        HttpContext = context,
                        Writer      = output,
                        RouteData   = new Microsoft.AspNetCore.Routing.RouteData()
                        {
                        },
                        ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                        {
                            Model = null
                        },
                        TempData         = new TempDataDictionary(context, _tempDataProvider), //ViewData
                        View             = viewResult.View,
                        FormContext      = new FormContext(),
                        ActionDescriptor = new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor()
                    };
                    //渲染
                    await viewResult.View.RenderAsync(viewContext);

                    html = output.ToString();
                }
            }
            var htmlDoc = new HtmlDocument();

            htmlDoc.LoadHtml(originalHtml);
            HtmlNode testNode = HtmlNode.CreateNode(html);
            var      htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");

            htmlBody.InsertBefore(testNode, htmlBody.FirstChild);

            string rawHtml = htmlDoc.DocumentNode.OuterHtml; //using this results in a page that displays my inserted HTML correctly, but duplicates the original page content.

            //rawHtml = "some text"; uncommenting this results in a page with the correct format: this text, followed by the original contents of the page

            return(rawHtml);
        }
        public async Task <string> RenderToStringAsync(string viewName, object model = null, bool isMainPage = true)
        {
            var actionContext = _actionContextAccessor.ActionContext;

            if (actionContext == null)
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext == null)
                {
                    httpContext = new DefaultHttpContext()
                    {
                        RequestServices = _serviceProvider
                    };
                }

                actionContext = new ActionContext(httpContext, httpContext.GetRouteData(), new ActionDescriptor());
            }

            var tempDataFactory = _serviceProvider.GetRequiredService <ITempDataDictionaryFactory>();
            var tempData        = tempDataFactory?.GetTempData(actionContext.HttpContext);

            if (tempData == null)
            {
                var tempDataProvider = _serviceProvider.GetRequiredService <ITempDataProvider>();
                tempData = new TempDataDictionary(actionContext.HttpContext, tempDataProvider);
            }

            var viewEngineResult = _viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage);

            if (!viewEngineResult.Success)
            {
                viewEngineResult = _viewEngine.FindView(actionContext, viewName, isMainPage);
            }
            viewEngineResult.EnsureSuccessful(originalLocations: null);
            var view = viewEngineResult.View;

            using var sw = new StringWriter();
            var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };
            var viewContext = new ViewContext(actionContext, view, viewDictionary, tempData, sw, _viewOptions.HtmlHelperOptions);

            await view.RenderAsync(viewContext);

            return(sw.ToString());
        }
Example #16
0
        // -----------

        ViewEngineResult FindView(string partialName)
        {
            var viewEngineResult = _viewEngine.GetView(ViewContext.ExecutingFilePath, partialName, isMainPage: false);
            var getViewLocations = viewEngineResult.SearchedLocations;

            if (!viewEngineResult.Success)
            {
                viewEngineResult = _viewEngine.FindView(ViewContext, partialName, isMainPage: false);
            }

            if (!viewEngineResult.Success)
            {
                var searchedLocations = Enumerable.Concat(getViewLocations, viewEngineResult.SearchedLocations);
                return(ViewEngineResult.NotFound(partialName, searchedLocations));
            }

            return(viewEngineResult);
        }
        //TODO document
        private async Task <IEnumerable <ComponentSampleSet> > GetViewModel(string path, IFileInfo file)
        {
            using var stream     = file.CreateReadStream();
            using var fileReader = new StreamReader(stream);
            using var writer     = new StringWriter();

            var viewPath = "~/" + path;

            ViewEngineResult viewResult = null;

            viewResult = _eng.GetView(viewPath, viewPath, false);

            // TODO this is a hack if I've ever seen one...
            // fill the view context with just enough to get the partial rendering
            var viewContext = new ViewContext
            {
                HttpContext      = HttpContext,
                RouteData        = RouteData,
                ActionDescriptor = ControllerContext.ActionDescriptor,
                FormContext      = new Microsoft.AspNetCore.Mvc.ViewFeatures.FormContext()
            };

            var rawContent = fileReader.ReadToEnd();
            // oh boy I sure hope this doesn't cause any issues... maybe there's a better way?
            var renderedContent = await new PartialTagHelper(_eng, _vbScope)
            {
                ViewContext = viewContext, Name = viewPath
            }.RenderTagHelperAsync();

            // separate out the examples
            var rawSamples      = SeparateExamples(rawContent, true);
            var renderedSamples = SeparateExamples(renderedContent, false);

            // match them up by index
            var combined = rawSamples.Join(renderedSamples,
                                           o => o.Title, i => i.Title,
                                           (raw, rendered) => new ComponentSampleSet {
                RawContent = raw, RenderedContent = rendered
            });

            return(combined);
        }
Example #18
0
        private async Task RenderPartialViewAsync(TextWriter writer)
        {
            var viewEngineResult = _viewEngine.GetView(ViewContext.ExecutingFilePath, Name, isMainPage: false);
            var getViewLocations = viewEngineResult.SearchedLocations;

            if (!viewEngineResult.Success)
            {
                viewEngineResult = _viewEngine.FindView(ViewContext, Name, isMainPage: false);
            }

            if (!viewEngineResult.Success)
            {
                var searchedLocations = Enumerable.Concat(getViewLocations, viewEngineResult.SearchedLocations);
                var locations         = string.Empty;
                if (searchedLocations.Any())
                {
                    locations += Environment.NewLine + string.Join(Environment.NewLine, searchedLocations);
                }

                throw new InvalidOperationException(
                          Resources.FormatViewEngine_PartialViewNotFound(Name, locations));
            }

            var view = viewEngineResult.View;
            // Determine which ViewData we should use to construct a new ViewData
            var baseViewData = ViewData ?? ViewContext.ViewData;

            // Use the rendering View's model only if an for expression does not exist
            var model              = For != null ? For.Model : ViewContext.ViewData.Model;
            var newViewData        = new ViewDataDictionary <object>(baseViewData, model);
            var partialViewContext = new ViewContext(ViewContext, view, newViewData, writer);

            if (For?.Name != null)
            {
                newViewData.TemplateInfo.HtmlFieldPrefix = newViewData.TemplateInfo.GetFullHtmlFieldName(For.Name);
            }

            using (view as IDisposable)
            {
                await view.RenderAsync(partialViewContext);
            }
        }
Example #19
0
        public async Task <IActionResult> Error(int code)
        {
            var model = new PostModel();

            model.Blog = await _db.CustomFields.GetBlogSettings();

            model.Blog.Cover = $"{Url.Content("~/")}{model.Blog.Cover}";

            var viewName = $"~/Views/Themes/{model.Blog.Theme}/Error.cshtml";
            var result   = _viewEngine.GetView("", viewName, false);

            if (result.Success)
            {
                return(View(viewName, model));
            }
            else
            {
                return(View("~/Views/Shared/_Error.cshtml", model));
            }
        }
Example #20
0
        public IRazorPage CreateRazorPage(string helpersViewPath, ViewContext viewContext)
        {
            var viewEngineResult = _viewEngine.GetView(viewContext.ExecutingFilePath, helpersViewPath, isMainPage: false);

            var originalLocations = viewEngineResult.SearchedLocations;

            if (!viewEngineResult.Success)
            {
                viewEngineResult = _viewEngine.FindView(viewContext, helpersViewPath, isMainPage: false);
            }

            if (!viewEngineResult.Success)
            {
                var locations = string.Empty;

                if (originalLocations.Any())
                {
                    locations = Environment.NewLine + string.Join(Environment.NewLine, originalLocations);
                }

                if (viewEngineResult.SearchedLocations.Any())
                {
                    locations += Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations);
                }

                throw new InvalidOperationException($"The Razor helpers view '{helpersViewPath}' was not found. The following locations were searched:{locations}");
            }

            var razorPage = ((RazorView)viewEngineResult.View).RazorPage;

            razorPage.ViewContext = viewContext;

            // we need to save and restore the original view data dictionary as it is changed by IRazorPageActivator.Activate
            // https://github.com/dotnet/aspnetcore/blob/v3.1.6/src/Mvc/Mvc.Razor/src/RazorPagePropertyActivator.cs#L59
            var originalViewData = viewContext.ViewData;

            try { _razorPageActivator.Activate(razorPage, viewContext); }
            finally { viewContext.ViewData = originalViewData; }

            return(razorPage);
        }
Example #21
0
        public IActionResult Entries(string id)
        {
            if (id == null)
            {
                return(Redirect("Index"));
            }

            //if redirected to Index alone the new route will be Blog/Entries/Index
            // and this will create a conflict in the browser
            //if (!id.Equals("Entrie1")) {return RedirectToAction("Index","Blog");};

            var viewName = $"~/Views/Blog/{id}.cshtml";
            var result   = _compositeViewEngine.GetView("", viewName, false);

            if (result.Success)
            {
                return(View(id));
            }

            return(View("MyNotFound"));
        }
        private async Task <string> GenerateBodyFromTemplateAsync(string templatePath, object model, string subject)
        {
            string body;

            using (StringWriter sw = new StringWriter())
            {
                // 这里渲染模板是不包含任何 http 请求的东西的, 所以模板里请不要使用 http 的东西哦
                var httpContext = new DefaultHttpContext();
                httpContext.RequestServices = ServiceProvider;
                var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
                var viewData      = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary());
                viewData.Model = model;
                var data        = new TempDataDictionary(actionContext.HttpContext, TempDataProvider);
                var viewResult  = CompositeViewEngine.GetView(null, templatePath, false);
                var viewContext = new ViewContext(actionContext, viewResult.View, viewData, data, sw, new HtmlHelperOptions());
                viewContext.ViewBag.Layout = EmailOptions.LayoutPath;
                viewContext.ViewBag.Title  = subject;
                await viewResult.View.RenderAsync(viewContext);

                body = sw.GetStringBuilder().ToString();
            }
            return(body);
        }
        public virtual void IterationSetup()
        {
            _requestScope = _serviceProvider.CreateScope();

            _viewEngineResult = _viewEngine.GetView(null, ViewPath, true);
            _viewEngineResult.EnsureSuccessful(null);

            _actionContext = new ActionContext(
                new DefaultHttpContext()
            {
                RequestServices = _requestScope.ServiceProvider
            },
                _routeData,
                _actionDescriptor);

            _tempData = _tempDataDictionaryFactory.GetTempData(_actionContext.HttpContext);

            _viewDataDictionary = new ViewDataDictionary(
                _requestScope.ServiceProvider.GetRequiredService <IModelMetadataProvider>(),
                _actionContext.ModelState);
            _viewDataDictionary.Model = Model;

            _executor = _requestScope.ServiceProvider.GetRequiredService <BenchmarkViewExecutor>();
        }
Example #24
0
 /// <summary>
 /// 获取视图
 /// </summary>
 /// <param name="compositeViewEngine">复合视图引擎</param>
 /// <param name="path">路径</param>
 /// <returns></returns>
 private ViewEngineResult GetView(ICompositeViewEngine compositeViewEngine, string path)
 {
     return(compositeViewEngine.GetView("~/", $"~{path}", true));
 }
        private async Task GetCode(HttpContext context)
        {
            Random rd = new Random();

            _PositionX = rd.Next(_MinRangeX, _MaxRangeX);
            _PositionY = rd.Next(_MinRangeY, _MaxRangeY);
            context.Session.SetInt32("code", _PositionX);
            context.Session.SetInt32("code_errornum", 0);
            int[]  a     = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
            int[]  array = a.OrderBy(x => Guid.NewGuid()).ToArray();
            Bitmap bmp;
            var    capchaPic = Path.Combine(path, (new Random()).Next(0, _ImgNum - 1) + ".jpg");
            var    filename  = Path.Combine(environment.ContentRootPath, capchaPic);

            if (!File.Exists(filename))
            {
                var embeddedFileProvider = new Microsoft.Extensions.FileProviders.EmbeddedFileProvider(this.GetType().Assembly, this.GetType().Assembly.GetName().Name);
                var allResources         = embeddedFileProvider.GetDirectoryContents(string.Empty);
                var embedFile            = embeddedFileProvider.GetFileInfo(capchaPic.Replace(Path.DirectorySeparatorChar, '.'));
                if (!embedFile.Exists)
                {
                    throw new ArgumentNullException("can not found captcha picture");
                }
                bmp = new Bitmap(embedFile.CreateReadStream());
            }
            else
            {
                bmp = new Bitmap(filename);
            }
            string ls_small     = "data:image/jpg;base64," + ImgToBase64String(cutImage(bmp, _shearSize, _shearSize, _PositionX, _PositionY));
            Bitmap lb_normal    = GetNewBitMap(bmp, _shearSize, _shearSize, _PositionX, _PositionY);
            string ls_confusion = "data:image/jpg;base64," + ImgToBase64String(ConfusionImage(array, lb_normal));
            var    captchaInfo  = new CaptchaInfo
            {
                Errcode = 0,
                Y       = _PositionY,
                Array   = string.Join(",", array),
                ImgX    = _ImgWidth,
                ImgY    = _ImgHeight,
                Small   = ls_small,
                Normal  = ls_confusion
            };

            /* errcode: 状态值 成功为0
             * y:裁剪图片y轴位置
             * small:小图字符串
             * normal:剪切小图后的原图并按无序数组重新排列后的图
             * array:无序数组
             * imgx:原图宽
             * imgy:原图高
             */

            var viewResult = viewEngine.GetView("~/", "~/Views/Shared/SlideCaptcha.cshtml", true);

            if (viewResult.Success)
            {
                //创建临时的StringWriter实例,用来配置到视图上下文中
                using (var output = new StringWriter())
                {
                    //视图上下文对于视图渲染来说很重要,视图中的前后台交互都需要它
                    var viewContext = new ViewContext()
                    {
                        HttpContext = context,
                        Writer      = output,
                        RouteData   = new Microsoft.AspNetCore.Routing.RouteData()
                        {
                        },
                        ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                        {
                            Model = captchaInfo
                        },
                        TempData         = new TempDataDictionary(context, tempDataProvider), //ViewData
                        View             = viewResult.View,
                        FormContext      = new FormContext(),
                        ActionDescriptor = new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor()
                    };
                    //渲染
                    await viewResult.View.RenderAsync(viewContext);

                    var html = output.ToString();
                    context.Response.ContentType = "text/html";
                    //输出到响应体
                    await context.Response.WriteAsync(html);
                }
            }
            else
            {
                await context.Response.WriteAsync(jsonHelper.Serialize(captchaInfo).ToString());
            }
        }
Example #26
0
        public async Task RenderAsync(ContentContext contentContext, TextWriter output)
        {
            if (contentContext == null)
            {
                throw new ArgumentNullException(nameof(contentContext));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            var contentView = viewLocator.FindView(contentContext.Explorer.Metadata.ModelType);

            if (contentView == null)
            {
                throw new InvalidOperationException($"Couldn't find content view {contentView.Name}");
            }

            var viewEngineResult = viewEngine.GetView("~/", contentView.Name, false);

            if (!viewEngineResult.Success)
            {
                throw new InvalidOperationException($"Couldn't find view {contentView.Name}");
            }
            var view = viewEngineResult.View;

            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = contentContext.Content
            };

            viewData.Add(ViewData_ContentContextKeyName, contentContext);

            var itemRenderingContext = new ViewRenderingContext();

            viewData.Add(ViewData_ViewRenderingContextKeyName, itemRenderingContext);

            using (var contentOutput = new StringWriter())
            {
                var http = contentContext.Services.GetRequiredService <IHttpContextAccessor>();

                var viewContext = new ViewContext
                {
                    HttpContext = httpContextAccessor.HttpContext,
                    ViewData    = viewData,
                    Writer      = contentOutput,
                    RouteData   = new RouteData()
                };

                await view.RenderAsync(viewContext);

                string tagName = "div";
                if (!string.IsNullOrEmpty(itemRenderingContext.HtmlTag))
                {
                    tagName = itemRenderingContext.HtmlTag;
                }

                var tag = new TagBuilder(tagName);
                if (!string.IsNullOrEmpty(itemRenderingContext.CssClass))
                {
                    tag.AddCssClass(itemRenderingContext.CssClass);
                }

                if (!string.IsNullOrEmpty(itemRenderingContext.ScriptName))
                {
                    tag.Attributes.Add("data-content-script", itemRenderingContext.ScriptName);
                }

                if (contentContext.Explorer.IsRoot)
                {
                    tag.Attributes.Add("content-root", string.Empty);
                }
                tag.Attributes.Add("content-type", contentContext.Explorer.Metadata.Name);
                tag.Attributes.Add("content-path", contentContext.Explorer.ModelPath);
                tag.Attributes.Add("content-path-index", contentContext.Explorer.Index.ToString());

                tag.InnerHtml.AppendHtml(contentOutput.ToString());

                tag.WriteTo(output, htmlEncoder);
            }
        }
Example #27
0
        private bool IsViewExists(string viewPath)
        {
            var result = _compositeViewEngine.GetView("", viewPath, false);

            return(result.Success);
        }
Example #28
0
        private async Task RenderToStringAsync(TextWriter writer, string templateName, object model, bool mainPage, bool partial, bool readOnly, object additionalViewData)
        {
            var httpContext = _httpContextAccessor.HttpContext ?? new DefaultHttpContext {
                RequestServices = _serviceProvider
            };
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            var newViewData = new ViewDataDictionary <object>(_modelMetadataProvider, new ModelStateDictionary())
            {
                Model = model
            };

            var newTempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider);



            if (mainPage || partial)
            {
                var result = _viewEngine.GetView(executingFilePath: null, viewPath: templateName, isMainPage: mainPage);
                if (!result.Success)
                {
                    result = _viewEngine.FindView(actionContext, templateName, isMainPage: mainPage);
                }

                if (!result.Success)
                {
                    throw new Exception($"A view with the name {templateName} could not be found");
                }

                var viewContext = new ViewContext(actionContext, result.View, newViewData, newTempData, writer, ViewOptions.HtmlHelperOptions)
                {
                    ExecutingFilePath = null
                };

                await viewContext.View.RenderAsync(viewContext); //Automatically writes out
            }
            else
            {
                var viewContext = new ViewContext()
                {
                    ExecutingFilePath = null,
                    View                            = null,
                    ViewData                        = newViewData,
                    TempData                        = newTempData,
                    Writer                          = writer,
                    FormContext                     = new FormContext(),
                    ClientValidationEnabled         = ViewOptions.HtmlHelperOptions.ClientValidationEnabled,
                    Html5DateRenderingMode          = ViewOptions.HtmlHelperOptions.Html5DateRenderingMode,
                    ValidationSummaryMessageElement = ViewOptions.HtmlHelperOptions.ValidationSummaryMessageElement,
                    ValidationMessageElement        = ViewOptions.HtmlHelperOptions.ValidationMessageElement,
                    ActionDescriptor                = actionContext.ActionDescriptor,
                    HttpContext                     = actionContext.HttpContext,
                    RouteData                       = actionContext.RouteData
                };

                var htmlHelper = MakeHtmlHelper(viewContext, newViewData);

                if (readOnly)
                {
                    //var htmlContent = htmlHelper.DisplayForModel(additionalViewData);
                    var htmlContent = htmlHelper.Display(null, templateName, null, additionalViewData);
                    htmlContent.WriteTo(writer, HtmlEncoder.Default);
                }
                else
                {
                    //var htmlContent = htmlHelper.EditorForModel(additionalViewData);
                    var htmlContent = htmlHelper.Editor(null, templateName, null, additionalViewData);
                    htmlContent.WriteTo(writer, HtmlEncoder.Default);
                }
            }
        }
Example #29
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="engine"></param>
 /// <param name="info"></param>
 /// <returns></returns>
 protected virtual ViewEngineResult GetView(ICompositeViewEngine engine, RouteInformation info)
 {
     return(engine.GetView("~/", $"~{info.Invocation}", !info.IsPartialView));
 }