• 拦截Response.Redirect的跳转并转换为Js的跳转


    有一个很常见的需求,某个页面需要用户登录才能访问,或者某个操作需要用户登录

    这就需要检测用户登录,一般是使用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';"}
  • 相关阅读:
    C++互斥器:Semaphores
    C++互斥器:Mutex
    内联函数(inline)
    C++显式转换
    线程同步控制
    拷贝构造函数——防篡改
    extern关键字
    虚析构、纯虚析构
    类的友元关系
    char 与 unsigned char的本质区别
  • 原文地址:https://www.cnblogs.com/wzxinchen/p/4309744.html
Copyright © 2020-2023  润新知