我有一个WCF REST服务,它接受一些参数并发送电子邮件。电子邮件的模板是MVC3操作。基本上我想将该动作呈现为字符串。
如果它是ASP.NET WebForm,我可以简单地使用Server.Execute(path, stringWriter, false)
。但是,当我插入行动路径时,我会得到Error executing child request
。
我可以从我的服务(AspNetCompatibilityRequirementsMode.Allowed
)完全访问HttpContext。
我知道还有其他答案可以在控制器的上下文中对字符串进行渲染操作。当我在那个世界之外但是仍然在同一台服务器上(并且,就此而言,在同一个应用程序中)时,我该怎么做?
答案 0 :(得分:3)
我根据几个不同的谷歌搜索拼凑了一个答案。它有效,但我并不是100%确定它尽可能精益。我会粘贴其他人试用的代码。
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();
}
}
}