我有一个生成电子邮件的系统。这些电子邮件的部分内容来自ParialViews。 在我的EmailController中,我希望能够通过调用它们的相关动作并插入View HTML来获取构成电子邮件模板区域的HTML代码段。
我已经在此处(Return View as String in .NET Core)上看到过有关该帖子的信息,但效果不佳...
下面的解决方案确实找到并尝试获取View HTML ,但是实际上并没有尝试执行View的controller动作。 由于视图是动态的,因此会导致错误。
因此,我可以执行 ControllerB.Action
,将其结果作为字符串从ControllerA.Action
中检索出来吗?
我当前的尝试: 服务:
public interface IViewRenderService
{
Task<string> RenderToStringAsync(string viewName, object model);
}
public class ViewRenderService : IViewRenderService
{
private readonly IRazorViewEngine _razorViewEngine;
private readonly ITempDataProvider _tempDataProvider;
private readonly IServiceProvider _serviceProvider;
public ViewRenderService(IRazorViewEngine razorViewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider)
{
_razorViewEngine = razorViewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
}
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())
{
var 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();
}
}
}
Starup.cs
services.AddScoped<IViewRenderService, ViewRenderService>();
控制器A
private readonly IViewRenderService _viewRenderService;
public ReportController(...
IViewRenderService viewRenderService)
{
...
_viewRenderService = viewRenderService;
}
来自控制器A的呼叫:
var theHtmlString = await _viewRenderService.RenderToStringAsync("ControllerB/Action1", new { parameters = paramsmodel });