在C#asp.net中,是否可以通过方法中途返回有效的网页?

时间:2010-07-15 16:15:33

标签: c# ajax asp.net-2.0

当我想将已失去会话状态的用户重定向回StartPage时,我发现Response.Redirect(“〜/ StartPage.aspx”)导致错误“无法在页面回调中调用响应重定向”。因此,在Page.IsCallback情况下,我想添加javascript来执行重定向 - 这是有效的 - 请参阅下面的代码。

protected void ForceBackToStartPage()
{
    if (Page.IsCallback)
    {
        string fullLoginUrl = ConvertRelativeUrlToAbsoluteUrl( "~/StartPage.aspx" );
        string script = string.Format("window.location.href = '{0}';", fullLoginUrl);
        ClientScriptManager cm = Page.ClientScript;
        cm.RegisterClientScriptBlock(GetType(), "redirect", script, true);
        //Response.Flush();
        //Response.End();
    }
    else
    {
        Response.Redirect("~/StartPage.aspx");
    }

}

我在本节中添加了javascript之后,代码继续正常处理,离开此功能并转到网页的其他处理部分 - 由于用户没有会话数据而探测到。理想情况下,我希望处理此网页以完成 - 并使页面返回有效状态,以便用户被重定向。

这可能吗?

我以为Response.Flush();到Response.End();可能会有所作为 - 但发送回浏览器的网页会导致XML Parse错误。

更多信息:我在几个地方检查丢失的会话数​​据(取决于网页 - 此代码在很多网页中) - 例如 - PageLoad和一些提交按钮方法。

在新方法之前,我使用了这个代码,例如:

protected void Page_Load(object sender, EventArgs e)
{
    if ((string)Session["OK"] != "OK")
    {
        // the session has timed out - take them back to the start page
        Response.Redirect("~/StartPage.aspx");
    }

...rest of processing

现在它被调用如下:

protected void Page_Load(object sender, EventArgs e)
{
    if ((string)Session["OK"] != "OK")
    {
        // the session has timed out - take them back to the start page
        ForceBackToStartPage();
    }

...rest of processing

所以我显然可以使用

否则 {  ...其余的处理 }

但是我希望不必这样做,因为SVN Source Control认为我已经重写了整个“剩余处理”部分。这是有问题的,因为当我从分支合并到主干时它没有检查我没有覆盖mod,因为它假设它是所有新代码。

2 个答案:

答案 0 :(得分:1)

Response.Redirect发出“302 Moved”命令,该命令无法异步提供。鉴于您只是在IsCallback = true时注册脚本,当IsCallback = false时,您是否也可以这样做?注册一个脚本,将事件挂钩到窗口的已加载事件,并从脚本而不是从服务器重定向页面。

答案 1 :(得分:1)

我最近再次考虑这个问题并且意识到了非常明显的答案。忘记结构良好的代码,作为错误陷阱的一部分这是一个特例,并在'ForceBackToStartPage'方法调用之后使用 return;

protected void Page_Load(object sender, EventArgs e)
{    
 if ((string)Session["OK"] != "OK")  
   {        
       // the session has timed out - take them back to the start page    
       ForceBackToStartPage();  
       return; 
   }  

...rest of processing

}