所以这就是问题所在:我正在通过将完整视图页面呈现为字符串并发送它们来构建要由我的应用程序发送的电子邮件。只要我之后不重定向到站点上的另一个 URL,这将毫无问题。每当我尝试时,我都会收到“System.Web.HttpException:发送 HTTP 标头后无法重定向”。
我相信问题出在我正在重用来自控制器操作的上下文的事实,创建电子邮件的调用来自该操作。更具体地说,来自上下文的 HttpResponse。不幸的是,我无法创建一个使用 HttpWriter 的新 HttpResponse,因为该类的构造函数无法访问,并且使用从 TextWriter 派生的任何其他类都会导致 response.Flush() 本身引发异常。
有人对此有解决方案吗?
public static string RenderViewToString(
ControllerContext controllerContext,
string viewPath,
string masterPath,
ViewDataDictionary viewData,
TempDataDictionary tempData)
{
Stream filter = null;
ViewPage viewPage = new ViewPage();
//Right, create our view
viewPage.ViewContext = new ViewContext(controllerContext,
new WebFormView(viewPath, masterPath), viewData, tempData);
//Get the response context, flush it and get the response filter.
var response = viewPage.ViewContext.HttpContext.Response;
//var response = new HttpResponseWrapper(new HttpResponse
// (**TextWriter Goes Here**));
response.Flush();
var oldFilter = response.Filter;
try
{
//Put a new filter into the response
filter = new MemoryStream();
response.Filter = filter;
//Now render the view into the memorystream and flush the response
viewPage.ViewContext.View.Render(viewPage.ViewContext,
viewPage.ViewContext.HttpContext.Response.Output);
response.Flush();
//Now read the rendered view.
filter.Position = 0;
var reader = new StreamReader(filter, response.ContentEncoding);
return reader.ReadToEnd();
}
finally
{
//Clean up.
if (filter != null)
filter.Dispose();
//Now replace the response filter
response.Filter = oldFilter;
}
}