在运行重定向之前等待代码执行

时间:2010-09-29 01:39:18

标签: c# redirect response.redirect

我有一个页面重定向,在使用WebClient和StringBuilder将字符串写入MSword文档后运行。

        HttpContext.Current.Response.Write(strHTMLContent);
        this.Page.Response.Redirect("http://www.google.com");
        HttpContext.Current.Response.End();

然而,由于重定向立即发生,因此字符串永远不会被写入(或者它没有机会)。

如何才能使重定向运行,直到发生字符串写入?

谢谢你们

这是用于生成MSWord的代码:

        HttpContext.Current.Response.Charset = "";
        HttpContext.Current.Response.ContentType = "application/msword";
        string strFileName = "GenerateDocument" + ".doc";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
        StringBuilder strHTMLContent = new StringBuilder();

2 个答案:

答案 0 :(得分:0)

重定向结束所有处理并指示浏览器指向下一步的位置。您可能想要做的是编写您希望用户看到的数据,但包括维基百科文章中概述的meta refresh或类似机制。

答案 1 :(得分:0)

如果我错了,请纠正我,但是如果他把这个放在try / catch /中,那么直到写回答之后才会执行刷新?

 try 
    {
      HttpContext.Current.Response.Write(strHTMLContent);
      HttpContext.Current.Response.End();
    }
 catch(Exception ex)
    {
      //handle exception
     }
 finally
     {
       this.Page.Response.Redirect("http://www.google.com");
     }