ExtAspNet应用技巧(三) 302与Asp.Net Ajax

问题描述:
mgzhenhong网友提到这样的问题
,并给出了示例:
1. Web.config启用Forms Authentication。
<authentication mode="Forms">
  
<forms name=".Test" loginUrl="~/Login.aspx" timeout="20" protection="All"></forms>
</authentication>
<authorization>
  
<deny users="?"/>
</authorization>

2. 登录页面(Login.aspx)放置一个按钮,点击按钮时模拟登录:
protected void Button1_Click(object sender, EventArgs e)
{
    FormsAuthentication.SetAuthCookie(
"AccountID"false);
    PageContext.Redirect(
"~/Default.aspx");
}

3. 主页面放置一个按钮,并在Page_Load时删除登录凭证:
protected void Page_Load(object sender, EventArgs e)
{
    FormsAuthentication.SignOut();
}
protected void Button1_Click(object sender, EventArgs e)
{
    
// nothing
}

4. 点击此按钮时应该会跳转到登录页面,但是由于使用了ExtAspNet出错了:


问题分析:
首先从Firebug提供的信息,我们知道在点击Default.aspx页面的按钮时的确发出了两次请求,第一次返回的是 302 Found,
第二次是重定向的登录页面。
这就使我想起了以前使用 Response.Redirect 的错误,和这个一模一样。以前我们的解决办法是告诉大家,以后不要使用Response.Redirect了,
使用我们ExtAspNet提供的方法 PageContext.Redirect ,但是现在似乎绕不过去了,有理由相信 Asp.Net 的Form Authentication内部调用了
Response.Redirect 函数,我们可能去修改Asp.Net的实现吧。

另辟蹊径:
既然绕不过 302 Found 的响应,我们何不来支持它,不过诡异的是在ExtAspNet的AJAX请求代码中:
Ext.Ajax.request({
    url: document.location.href,
    params: serializeForm(theForm.id),
    success: _ajaxSuccess,
    failure: _ajaxFailure
});
两次的HTTP请求变成了一次,并且在回调函数(_ajaxSuccess)中观察状态码是 200, 而不是 302。
无奈之下只好借助网络,发现了下面一篇文章:
http://extjs.com/forum/showthread.php?t=30278
最终的结论居然是:
Unfortunately basex can't handle 302 as the browser preempts it.
Bottom line - redirects considered harmful with ExtJS and other AJAX frameworks.
上面一句话的重点在 Preempt 单词上,我特地查了一下这个单词的意思是“vt. 优先购买(先取)”,看来 302 响应是被
浏览器无情的劫持了,XMLHTTPREQUEST看到的是一个完整的HTTP请求响应。

看来客户端无法解决这个问题。

峰回路转:
服务器端总能有办法吧,我们可以在响应流中捕获 302 ,然后进行一定的处理再输出到浏览器。
实事上 httpModules 就不是做这个事情的么,在我开始编码之前我偷了点懒,我们这么普遍的问题Asp.Net Ajax应该已经实现了吧,
果然如此,在\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\Source\System.Web.Extensions\Handlers\ScriptModule.cs
我看到了久违的 302 :
private void PreSendRequestHeadersHandler(object sender, EventArgs args) {
    HttpApplication application = (HttpApplication)sender;
    HttpResponse response = application.Response;

    
if (response.StatusCode == 302) {
        
// .
    }
}

我们就照葫芦画瓢自己实现一个ExtAspNet.ScriptModule:
public class ScriptModule : IHttpModule
{

    
private void PreSendRequestHeadersHandler(object sender, EventArgs args)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpResponse response = application.Response;

        
if (response.StatusCode == 302)
        {
            
if (ResourceManager.IsExtAspNetAjaxPostBack2(application.Request))
            {
                
string redirectLocation = response.RedirectLocation;
                List<HttpCookie> cookies = new List<HttpCookie>(response.Cookies.Count);
                
for (int i = 0; i < response.Cookies.Count; i++)
                {
                    cookies.Add(response.Cookies[i]);
                }


                response.ClearContent();
                response.ClearHeaders();
                
for (int i = 0; i < cookies.Count; i++)
                {
                    response.AppendCookie(cookies[i]);
                }
                response.Cache.SetCacheability(HttpCacheability.NoCache);
                response.ContentType = "text/plain";
                response.Write(String.Format("window.location.href='{0}';", redirectLocation));
            }
        }
    }

    
#region IHttpModule 成员

    
public void Dispose()
    {

    }

    
public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += new EventHandler(PreSendRequestHeadersHandler);
    }

    
#endregion
}

这样一来,把以前遗留的 Response.Redirect 不能使用的问题也解决了,现在想跳转页面既可以使用 Response.Redirect
也可以使用 PageContext.Redirect, 并且和 Asp.Net 的Form Authentication 也兼容了。

=============================================================
现在我们再把这篇文章开头部分的例子重新描述一下:
1. Web.config启用Forms Authentication。
<?xml version="1.0"?>
<configuration>
  
<configSections>
    
<section name="ExtAspNet" type="ExtAspNet.ConfigSection, ExtAspNet"/>
  
</configSections>
  
<system.web>

    
<pages>
      
<controls>
        
<add assembly="ExtAspNet" namespace="ExtAspNet" tagPrefix="ext"/>
      
</controls>
    
</pages>

    
<httpModules>
      
<add name="ScriptModule" type="ExtAspNet.ScriptModule, ExtAspNet"/>
    
</httpModules>

    
<authentication mode="Forms">
      
<forms name=".Test" loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx" timeout="20" protection="All"></forms>
    
</authentication>
    
<authorization>
      
<deny users="?"/>
    
</authorization>
    
    
<compilation debug="true"/>
  
</system.web>
</configuration>


2. 登录页面(Login.aspx)放置一个按钮,点击按钮时模拟登录:
protected void Button1_Click(object sender, EventArgs e)
{
    FormsAuthentication.RedirectFromLoginPage("AccountID"false);
}

3. 主页面放置一个按钮,并在Page_Load时删除登录凭证:
protected void Page_Load(object sender, EventArgs e)
{
    FormsAuthentication.SignOut();
}
protected void Button1_Click(object sender, EventArgs e)
{
    
// nothing
}

4. 点击此按钮时跳转到登录页面。

enjoy coding.

本文章示例源代码

注:请从SVN下载最新ExtAspNet源代码。
原文地址:https://www.cnblogs.com/sanshi/p/1531440.html