有一個很常見的需求,某個頁面需要用戶登錄才能訪問,或者某個操作需要用戶登錄
這就需要檢測用戶登錄,一般是使用Ajax去檢測是否登錄,當用戶未登錄時跳轉到登錄頁面
那么問題來了····
有的時候我們跳轉到登錄是直接Redirect,而有的時候因為是使用的Ajax,所以直接必須在客戶端用Js使用location.href進行跳轉
網上找了好久···找不到,然后想起Ext.Net實現了這個需求
就直接參考了Ext.Net的實現,也就是根據需求攔截Response.Redirect的跳轉並轉換為location.href
直接上代碼
1 public class AjaxHttpModule : IHttpModule 2 { 3 public void Dispose() 4 { 5 throw new NotImplementedException(); 6 } 7 8 public void Init(HttpApplication context) 9 { 10 context.PreSendRequestHeaders += context_PreSendRequestHeaders; 11 } 12 13 void context_PreSendRequestHeaders(object sender, EventArgs e) 14 { 15 HttpApplication application = sender as HttpApplication; 16 HttpContext context = application.Context; 17 if ((context.Response.StatusCode == 0x12e) && (context.Request.Headers.AllKeys.Contains("X-Requested-With"))) 18 { 19 string redirectLocation = context.Response.RedirectLocation; 20 context.Response.ClearContent(); 21 context.Response.StatusCode = 200; 22 context.Response.ContentType = "text/html"; 23 context.Response.Charset = "utf-8"; 24 context.Response.Headers.Remove("location"); 25 context.Response.Output.Write("{\"script\":\"window.location.href='" + redirectLocation + "';\"}"); 26 } 27 } 28 }
代碼很簡單,當檢測到響應到狀態碼為302並且是一個Ajax請求時,則自定義響應內容
將跳轉的地址拼接為一個json字符串由客戶端解析,最終解析結果為
{script:"window.location.href='/game/Play';"}