asp.net-mvc - 将 View 渲染为字符串,然后重定向会导致异常

标签 asp.net-mvc redirecttoaction httpexception

所以问题是:我正在通过将完整 View 页面渲染为字符串并发送它们来构建要由我的应用程序发送的电子邮件。只要我之后不重定向到该网站上的另一个 URL,此操作就不会出现任何问题。每当我尝试时,我都会收到“System.Web.HttpException:发送 HTTP header 后无法重定向。”

我认为问题来自于我正在重用 Controller 操作中的上下文,其中创建电子邮件的调用来自于此。更具体地说,来自上下文的 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;
        }
    }

最佳答案

您必须发起新请求。 位,你真的想用这种方式同步发送电子邮件吗?如果邮件服务器宕机,用户可能会等待很长一段时间。

我总是将电子邮件放入离线队列中并让服务邮寄它们。您可以考虑为此使用 Spark 模板引擎。

另一种方法是不重定向,而是写出带有元重定向标记的页面

关于asp.net-mvc - 将 View 渲染为字符串,然后重定向会导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1149068/

相关文章:

asp.net-mvc - 在 ASP.NET MVC 中,返回 RedirectToAction 时保留 URL

ASP.NET 如何获取 HttpException 错误代码

c# - 从 Application_Error 抛出 http 异常(未经授权)

c# - 在 Web API 中使用 RedirectToAction

jQuery 阻止 RedirectToAction 工作?

html - 隐藏 mvc 4 中特定页面的垂直滚动条

jquery - 如何在我的模型中对图表数据进行硬编码,然后让我的 Controller 从那里拉出它来显示它。使用 Highcharts

python - 从stravalib函数捕获python3中的HTTP错误

c# - 异步 ASP.Net MVC Controller 操作中的 Task.Run()

asp.net-mvc - ASP.NET MVC jquery checkboxlist 帖子?