Create a httpmodule and session authentification

1. Add following into web.config.

  <system.web>
    <httpModules>
      <add name="CustomAuthorizationModule" type="TstHttpModule.CustomAuthorizationModule" />
    </httpModules>

2. Create a class into appdata folder

2.1 Session is not null for the first time.

2.2 OnAcquireRequestState event will be fired for more than one time. Requested css and icon files will also call this event, however, the session is null at that time. Specific requested page can be saw with following statement.

string path = context.Request.Url.AbsolutePath;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TstHttpModule
{
    public class CustomAuthorizationModule : IHttpModule
    {
        public void Init(HttpApplication context){
            context.AcquireRequestState += OnAcquireRequestState;
        }

        public void Dispose(){
        }

        private void OnAcquireRequestState(object sender, EventArgs e){
            var context = ((HttpApplication)sender).Context;
            string path = context.Request.Url.AbsolutePath;
            if (context.Session == null){

            }
            else{
                if (context.Session["UserID"] == null){
                    context.Session["UserID"] = "abc";
                }
                else {
                    var t = context.Session["UserID"];
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/webglcn/p/2703792.html