Основываясь на ответе Райана, я сделал метод расширения:
public static string RenderViewToString(this Controller source, string viewName)
{
var viewEngineResult = ViewEngines.Engines.FindView(source.ControllerContext, viewName, null);
using (StringWriter output = new StringWriter())
{
viewEngineResult.View.Render(new ViewContext(source.ControllerContext, viewEngineResult.View, source.ViewData, source.TempData, output), output);
viewEngineResult.ViewEngine.ReleaseView(source.ControllerContext, viewEngineResult.View);
return output.ToString();
}
}
Для вызова изнутри действия контроллера (пример использования):
[AllowAnonymous]
public class ErrorController : Controller
{
// GET: Error
public ActionResult Index(System.Net.HttpStatusCode id)
{
Exception ex = null; // how do i get the exception that was thrown?
if (!Debugger.IsAttached)
Code.Email.Send(ConfigurationManager.AppSettings["BugReportEmailAddress"],
$"Bug Report: AgentPortal: {ex?.Message}",
this.RenderViewToString("BugReport"));
Response.StatusCode = (int)id;
return View();
}
}