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();
}
}
网友评论