ASP.NET 登录验证 ihttpmoudle

问题:

1.iis版本不同(IIS7.0,应用程序池采用的是集成模式,换成经典模式才起作用.)

在 IIS 7 以下的版本中,应用以下配置:

<system.web>
  <httpModules>
    <add name="Cftea.MyHttpModule" type="CfteaHttpModule程序集" />
  </httpModules>
</system.web>

在 IIS 7 及以上的版本中,应用以下配置

<system.webServer>
  <modules>
    <add name="Cftea.MyHttpModule" type="CfteaHttpModule程序集" />
  </modules>
</system.webServer>

<add name="命名空间.名字" type="程序集名字" />

例如:

<add name="web.common.MyModule" type="web" />

2.具体实现

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

namespace login.common
{
public class MyMoudle : IHttpModule
{
public void Dispose()
{
throw new NotImplementedException();
}

public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}

private void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication ha = (HttpApplication)sender;
int length = ha.Context.Request.Url.Segments.Length;
string a = ha.Context.Request.RawUrl;
string path = ha.Context.Request.Url.Segments[length - 1].ToString(); //获得访问的页面
bool IsLogingPage = path.ToLower().Equals("login.aspx"); //比较是否是Login.aspx 是就不进入
if (!IsLogingPage)
{
//var CookiesDemo = ha.Context.Request.Cookies["UserID"];
var CookiesDemo = ha.Session["UserID"];
if (CookiesDemo == null ||CookiesDemo.Equals(""))
{

//ha.Context.Response.Redirect("/Login.aspx");
ha.Context.Response.Write("<script>alert('login failed!');url='/login.aspx?url="+ a + "';if(window.parent!=null){window.parent.location=url;}else{this.location=url;};</script>");
ha.Context.Response.End();
}
}else
{
}
}
}
}
原文地址:https://www.cnblogs.com/uftwkb24/p/9984306.html