ASP.NET 使用web.config配置文件的system.webServer/modules标签实现登录验证

前言

  • modules 标签允许你添加、删除或配置在 IIS 中运行的 HTTP 模块。HTTP 模块是处理 HTTP 请求和响应的组件,它们可以在请求处理管道的不同阶段执行代码。
  • 某些 system.webServer 中的设置可能只适用于 IIS 的特定模式(如集成模式),而不适用于其他模式(如经典模式)
  • 当你需要扩展 IIS 的功能或自定义 HTTP 请求/响应处理流程时,可以使用 modules 标签来添加自定义的 HTTP 模块
  • 请注意,修改 IIS 配置可能会影响到网站或应用程序的行为和安全性
  • 使用场景:多个应用系统,使用同一个登录模块

1、Web.config配置文件

注意:以下内容为部分配置,不是整个web.config的配置

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
	<!--指定配置文件读取类-->
    <section name="MyLoginCheck" type="Login.Client.ConfigReader,Login.Client"/>
  </configSections>

  <MyLoginCheck>
    <!--配置项-->
    <add key="setting1" value="value11" />
    <add key="setting2" value="value22" />
  </MyLoginCheck>
  
  <system.webServer>
    <modules>
      <!--配置http请求预处理模块-->
      <add name="LoginClientHttpModule" type="Login.Client.LoginCheck,Login.Client" />
    </modules>
  </system.webServer>
</configuration>

2、配置读取类

cs 复制代码
using System.Collections.Generic;
using System.Configuration;
using System.Xml;

namespace Login.Client
{
    public class ConfigReader : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            var settings = new Dictionary<string, string>();
            foreach (XmlNode child in section.ChildNodes)
            {
                //<add key="" value=""/>属于XmlNodeType.Element
                if (child.NodeType == XmlNodeType.Element)
                {
                    var key = child.Attributes["key"]?.Value;
                    var value = child.Attributes["value"]?.Value;
                    if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                    {
                        settings.Add(key, value);
                    }
                }
            }

            return settings; // 返回解析后的配置数据
        }


        private static object locker = new object();
        private static Dictionary<string, string> _loginSetting;
        /// <summary>
        /// 配置键值对
        /// </summary>
        public static Dictionary<string, string> LoginSetting
        {
            get
            {
                if (_loginSetting == null)
                {
                    lock (locker)
                    {
                        if (_loginSetting == null)
                        {
                            _loginSetting = (Dictionary<string, string>)ConfigurationManager.GetSection("MyLoginCheck");
                        }
                    }
                }
                return _loginSetting;
            }
        }

    }
}

3、登录校验类

cs 复制代码
using Newtonsoft.Json;
using System;
using System.Web;
using System.Xml;

namespace Login.Client
{
    public class LoginCheck : IHttpModule
    {
        public void Dispose()
        {
            
        }

        public void Init(HttpApplication context)
        {
            // 使用AcquireRequestState:当ASP.NET获取与当前的请求相关联的当前状态(例如会话状态)
            context.AcquireRequestState += new EventHandler(Check);
        }
        

        private void Check(Object source, EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext context = application.Context;//context.Session 获取会话

            // 尝试从集合中获取设置值
            if (ConfigReader.LoginSetting == null)
            {
                return;
            }
            string setting1 = ConfigReader.LoginSetting["setting1"]?.ToString();
            string setting2 = ConfigReader.LoginSetting["setting2"].ToString();
            
            if (isLogin())
            {
                // 用户未登录,重定向到登录页面
                context.Response.Redirect(setting1, true);
            }

        }
		
		private bool isLogin(){
			//这里替换为判断是否登录逻辑
			return false;
		}

    }
}
相关推荐
-银雾鸢尾-5 分钟前
C#中的StringBuilder相关方法
开发语言·c#
心平气和量大福大4 小时前
C#-WPF-Window主窗体
开发语言·c#·wpf
白露与泡影5 小时前
Arthas 实战指南:从方法耗时定位到 JVM 变量热修改
服务器·jvm·c#
EIP低代码平台9 小时前
EIP低代码平台系统-字典功能讲解
低代码·c#·工作流
吉普赛的歌10 小时前
YARP负载均衡配置了多个相同接口导致的报错
c#·yarp
张人玉12 小时前
C# WinForms——工厂管理系统(C# WinForms)
数据库·sqlite·c#·winform
夜莺悠吟13 小时前
关于对 C# 中 ImplicitUsings,GlobalUsings 的讨论
c#·.net
不正经学生13 小时前
C 语言函数深入剖析(基础篇)—— 从零理解函数的每一个细节
c语言·开发语言·数据结构·算法·c#
-银雾鸢尾-20 小时前
C#中的拓展方法
开发语言·c#
EIP低代码平台1 天前
EIP低代码平台-系统参数配置详解|落地三级等保+高灵活私有化部署方案
低代码·c#·权限·工作流·netcore