I have a ASP.NET MVC controller with a bunch of action methods returning ViewResult. Now, I need to be able to change the result of the action based on a certain URL parameter in the following way:
- If the parameter is not present, just return the
ViewResult
as it is - If the parameter is present, take the
ViewResult
from the action that was just executed, render the view into a string, and returnFileStreamResult
containing this string (raw HTML) + some additional info (not relevant for the question)
I've tried to do this by overriding OnActionExecuted
in my controller:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var viewResult = filterContext.Result as ViewResult;
if (viewResult != null /* && certain URL param present*/)
{
string rawHtml = RenderViewIntoString(viewResult);
filterContext.Result = new FileStreamResult(new MemoryStream(Encoding.UTF8.GetBytes(rawHtml)), "application/octet-stream");
}
}
But I can't find a way to implement RenderViewIntoString
, because for some reason viewResult.View
is null
here.
How can I render the view into a string here?