public ViewEngineResult GetPageFromPathInfo(string pathInfo) { if (pathInfo.EndsWith("/")) { pathInfo += "default.cshtml"; } var viewPath = "~/wwwroot".CombineWith(pathInfo); if (!viewPath.EndsWith(".cshtml")) { viewPath += ".cshtml"; } var viewEngineResult = ViewEngine.GetView("", viewPath, isMainPage: viewPath == "~/wwwroot/default.cshtml"); if (!viewEngineResult.Success) { viewPath = PagesPath.CombineWith(pathInfo); if (!viewPath.EndsWith(".cshtml")) { viewPath += ".cshtml"; } viewEngineResult = ViewEngine.GetView("", viewPath, isMainPage: viewPath == $"{PagesPath}/default.cshtml"); } return(viewEngineResult.Success ? viewEngineResult : null); }
public async Task <string> ViewToStringAsync <T>(string viewName, T model) { var context = _ActionContextAccessor.ActionContext; if (context == null) { throw new ArgumentNullException(nameof(context)); } var result = new ViewResult() { ViewData = new ViewDataDictionary( metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary()) { Model = model, }, TempData = new TempDataDictionary( context.HttpContext, _TempDataProvider), ViewName = viewName, }; if (ViewEngine == null) { throw new ArgumentNullException(nameof(ViewEngine)); } var viewEngineResult = ViewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true); if (viewEngineResult.View == null) { throw new ArgumentNullException(nameof(viewEngineResult.View)); } using (var output = new StringWriter()) { var viewContext = new ViewContext( context, viewEngineResult.View, new ViewDataDictionary( metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary()) { Model = model }, new TempDataDictionary( context.HttpContext, _TempDataProvider), output, new HtmlHelperOptions()); await viewEngineResult.View.RenderAsync(viewContext); return(output.ToString()); } }
///// <summary> Find a view by a specific path and filename. </summary> ///// <param name="filepath"> The filepath. </param> ///// <returns> The found view. </returns> //x private IFileInfo _FindView(string filepath) //{ // IFileInfo result = null; // foreach (var fp in RazorViewEngineOptions.FileProviders) // { // result = fp.GetFileInfo(filepath); // if (result?.Exists == true) return result; // } // return result ?? new NotFoundFileInfo(filepath); //} /// <summary> Using a base path and type name find a view file. </summary> /// <exception cref="FileNotFoundException"> Thrown when the requested file is not present. </exception> /// <param name="searchPaths"> The locations to search under (without the filename). </param> /// <param name="name"> Name of the type to find a nested view for. </param> /// <param name="required"> /// (Optional) True if the view is required. If required and not found an exception will be thrown. Default is true. /// </param> /// <returns> The found view. </returns> private ViewEngineResult _FindView(IEnumerable <string> searchPaths, string name, bool required = true) { List <string> filenames = new List <string>(); filenames.Add(Path.ChangeExtension(name, "cshtml")); // (put the most likely one first) filenames.Add(Path.ChangeExtension(name, "cs.cshtml")); filenames.Add(name); List <string> locationsSearched = new List <string>(); ViewEngineResult result = null; // ... detect if this is a base path, or path with a file name ... // ('GetView()' expects the base path to end with '/', otherwise the last path name will be truncated off) var _searchPaths = searchPaths.ToArray(); for (int i = 0, n = _searchPaths.Length; i < n; ++i) { var searchPath = _searchPaths[i]; if (string.IsNullOrWhiteSpace(Path.GetExtension(searchPath)) && !searchPath.EndsWith("/")) { searchPath += "/"; } foreach (var filename in filenames) { result = ViewEngine.GetView(searchPath, filename, false); if (result.Success) { return(result); } else { locationsSearched.AddRange(result.SearchedLocations); } } } if (required) { throw new FileNotFoundException("Failed to find view '" + name + "'. Locations searched: " + Environment.NewLine + " > " + string.Join(Environment.NewLine + " > ", locationsSearched)); } else { return(null); } }
public async Task <string> Render <TModel>(string viewPath, TModel model, Action <dynamic> viewBagConsumer = null) { var viewEngineResult = ViewEngine.GetView(null, viewPath, false); if (!viewEngineResult.Success) { throw new InvalidOperationException($"Couldn't find view {viewPath}"); } var view = viewEngineResult.View; using (var output = new StringWriter()) { var httpContext = new DefaultHttpContext { RequestServices = HttpContextAccessor.HttpContext.RequestServices, User = HttpContextAccessor.HttpContext.User }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); var viewContext = new ViewContext( actionContext, view, new ViewDataDictionary <TModel>( metadataProvider: new EmptyModelMetadataProvider(), modelState: new ModelStateDictionary()) { Model = model }, new TempDataDictionary( httpContext, (ITempDataProvider)httpContext.RequestServices.GetService(typeof(ITempDataProvider))), output, new HtmlHelperOptions()); if (viewBagConsumer != null) { viewBagConsumer(viewContext.ViewBag); } await view.RenderAsync(viewContext); return(output.ToString().Trim()); } }
private ViewEngineResult FindView(IEnumerable <string> viewNames, out Dictionary <string, object> routingArgs) { routingArgs = null; const string execPath = ""; foreach (var viewName in viewNames) { if (viewName.StartsWith("/")) { var viewEngineResult = GetPageFromPathInfo(viewName); if (viewEngineResult.Success) { return(viewEngineResult); } viewEngineResult = GetRoutingPage(viewName, out routingArgs); if (viewEngineResult.Success) { return(viewEngineResult); } } else { foreach (var location in ViewLocations) { var viewPath = location.CombineWith(viewName) + ".cshtml"; var viewEngineResult = ViewEngine.GetView(execPath, viewPath, isMainPage: false); if (viewEngineResult.Success) { return(viewEngineResult); } } } } return(null); }