ASP.NET Core调用另一个控制器并生成返回视图的html
C# 全选
var articleController = this.HttpContext.RequestServices.GetService(typeof(YESCMS.Controllers.ArticleController)) as YESCMS.Controllers.ArticleController;
//获取结果
var actionResult = articleController.DocList(v.Category);
//判断结果是否是一个ViewResult
if (actionResult is ViewResult)
{
ViewResult viewResult = actionResult as ViewResult;
var routeData = new RouteData();
routeData.Values.Add("controller", "Article");
routeData.Values.Add("action", "DocList");
var serviceProvider = this.HttpContext.RequestServices.GetService(typeof(IServiceProvider)) as IServiceProvider;
var httpContext = new DefaultHttpContext { RequestServices = serviceProvider };
//var actionContext = new ActionContext(httpContext, routeData, new ActionDescriptor());
var actionContext = new ActionContext(httpContext, routeData, articleListAction);
//actionContext.ActionDescriptor = articleListAction;
//下面的代码就是执行这个ViewResult,并把结果的html内容放到一个StringBuiler对象中
var services = this.HttpContext.RequestServices;
var viewEngine = services.GetService(typeof(Microsoft.AspNetCore.Mvc.ViewEngines.ICompositeViewEngine)) as Microsoft.AspNetCore.Mvc.ViewEngines.ICompositeViewEngine;
Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult result = viewEngine.FindView(actionContext, viewResult.ViewName, true);
//var executor = services.GetRequiredService<ViewResultExecutor>();
var option = services.GetRequiredService<IOptions<MvcViewOptions>>();
//var result = executor.FindView(context, viewResult);
result.EnsureSuccessful(originalLocations: null);
var view = result.View;
StringBuilder builder = new StringBuilder();
var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
viewDictionary.Model = viewResult.Model;
var tempDataProvider = services.GetService<ITempDataProvider>();
var tempData = new TempDataDictionary(actionContext.HttpContext, tempDataProvider);
using (var writer = new StringWriter(builder))
{
var viewContext = new ViewContext(
actionContext,
view,
viewDictionary,
tempData,
writer,
option.Value.HtmlHelperOptions);
view.RenderAsync(viewContext).GetAwaiter().GetResult();
//这句一定要调用,否则内容就会是空的
writer.Flush();
}
string html = builder.ToString();
}
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员