Render an MVC3 action to a string from a WCF REST service method

廉价感情. 提交于 2019-12-04 20:33:06

I cobbled together an answer based on several different google searches. It works, but I'm not 100% sure it's as lean as it could be. I'll paste the code for others to try.

string GetEmailText(TemplateParameters parameters) {
    // Get the HttpContext
    HttpContextBase httpContextBase = 
        new HttpContextWrapper(HttpContext.Current);
    // Build the route data
    var routeData = new RouteData();
    routeData.Values.Add("controller", "EmailTemplate");
    routeData.Values.Add("action", "Create");

    // Create the controller context
    var controllerContext = new ControllerContext(
        new RequestContext(httpContextBase, routeData), 
        new EmailTemplateController());

    var body = ((EmailTemplateController)controllerContext.Controller)
               .Create(parameters).Capture(controllerContext);
    return body;
}

// Using code from here:
// http://blog.approache.com/2010/11/render-any-aspnet-mvc-actionresult-to.html
public class ResponseCapture : IDisposable
{
    private readonly HttpResponseBase response;
    private readonly TextWriter originalWriter;
    private StringWriter localWriter;
    public ResponseCapture(HttpResponseBase response)
    {
        this.response = response;
        originalWriter = response.Output;
        localWriter = new StringWriter();
        response.Output = localWriter;
    }
    public override string ToString()
    {
        localWriter.Flush();
        return localWriter.ToString();
    }
    public void Dispose()
    {
        if (localWriter != null)
        {
            localWriter.Dispose();
            localWriter = null;
            response.Output = originalWriter;
        }
    }
}
public static class ActionResultExtensions
{
    public static string Capture(this ActionResult result, ControllerContext controllerContext)
    {
        using (var it = new ResponseCapture(controllerContext.RequestContext.HttpContext.Response))
        {
            result.ExecuteResult(controllerContext);
            return it.ToString();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!