代码之家  ›  专栏  ›  技术社区  ›  yu yang Jian

使用httpmodule和会话身份验证,但img src导致会话为空

  •  0
  • yu yang Jian  · 技术社区  · 8 年前

    我想办法通过 IHttpModule 和 Session ,

    这个 context_PreRequestHandlerExecute 将截获早于控制器中操作的所有请求:

    1. add AuthenticModule class
    
    public class AuthenticModule : IHttpModule
    {
        public void Dispose()
        {
        }
    
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }     
    
        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication ha = (HttpApplication)sender;
            string path = ha.Context.Request.Url.ToString();
            int n = path.ToLower().IndexOf("login");
            if (n == -1 ) //if not login page 
            {
                //if user not login (doesn't have session)
                if(HttpContext.Current.Session["user"] == null) 
                {   //redirect to Login page
                    ha.Context.Response.Redirect("~/Home/Login");
                }
            }
        }
    } 
    
    2. add AuthenticModule to web.config
    
    <system.webServer>
     <modules>
      <add name="AuthenticModule" type="NAMESPACE.AuthenticModule, ASSEMBLY_NAME"></add>
     </modules>
    </system.webServer>
    

    但我有个问题,假设我有 /Home/Login 和 Home/Index 页数 HomeController ,以及的HTML 主页/索引 孔蒂安页 <img src="/IMG/tree.jpg" /> :

    public class HomeController : Controller
    {
        public ActionResult Login()
        {
            Session["user"] = "user";
            return Content("Logining");
        }
        public ActionResult Index()
        {
            return View();
        }
    }
    
    and Home/Index Page contians <img src="/IMG/tree.jpg" />
    

    然后,

    首先转到url /主页/登录 ,然后它将进入 上下文执行 ,因为url包含“login”,所以它只需传递,然后进入 Login() action,它将设置会话,这意味着这里的simple登录成功。

    我的问题是,如果我跑 /Home/Index , the <img src=“/img/tree.jpg”/> 也会将请求发送到 上下文执行 ,我发现 它的 HttpContext.Current.Session 为空,并导致 Session["user"] 空引用异常

    因此,只要任何页面包含 img src 对服务器自身映像的引用。

    有什么可以改进的吗 IHTTP模块 即使页面包含 IMG型钢 引用服务器自身映像?还是一条死胡同?

    0 回复  |  直到 8 年前