漫步者 - 技术日志

人,孰能无惑
  首页  :: 新随笔  :: 订阅 订阅  :: 管理

在ASP.NET 中实现单点登录

Posted on 2006-01-05 12:24  漫笔者  阅读(558)  评论(2)    收藏  举报
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace eMeng.Exam
{
/// <summary>
/// SingleLogin 的摘要说明。
/// 实现单点登录
/// </summary>

public class SingleLogin : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox UserName;
protected System.Web.UI.WebControls.TextBox PassWord;
protected System.Web.UI.WebControls.Label Msg;
protected System.Web.UI.WebControls.Button Login;

private void Page_Load(object sender, System.EventArgs e)
{
// 实际例子可访问:
// http://dotnet.aspx.cc/Exam/SingleLogin.aspx
}


Web 窗体设计器生成的代码

private void Login_Click(object sender, System.EventArgs e)
{
// 作为唯一标识的Key,应该是唯一的,这可根据需要自己设定规则。
// 做为测试,这里用用户名和密码的组合来做标识;也不进行其它的错误检查。

// 生成Key
string sKey = UserName.Text + "_" + PassWord.Text;
// 得到Cache中的给定Key的值
string sUser = Convert.ToString(Cache[sKey]);
// 检查是否存在
if (sUser == null || sUser == String.Empty)
{
// Cache中没有该Key的项目,表名用户没有登录,或者已经登录超时
// 注意下面使用的TimeSpan构造函数重载版本的方法,是进行是否登录判断的关键。
TimeSpan SessTimeOut = new TimeSpan(0,0,System.Web.HttpContext.Current.Session.Timeout,0,0);
HttpContext.Current.Cache.insert(sKey,sKey,
null,DateTime.MaxValue,SessTimeOut,
System.Web.Caching.CacheItemPriority.NotRemovable,
null);
Session[
"User"= sKey;
// 首次登录,您可以做您想做的工作了。
Msg.Text="<h4 style='color:red'>嗨!欢迎您访问<a href='http://dotnet.aspx.cc/'>【孟宪会之精彩世界】"
Msg.Text 
+= "</a>,祝您浏览愉快!:)</h4>";
}

else
{
// 在 Cache 中发现该用户的记录,表名已经登录过,禁止再次登录
Msg.Text="<h4 style='color:red'>抱歉,您好像已经登录了呀:-(</h4>";
return;
}

}

}

}

From: http://dotnet.aspx.cc/ShowDetail.aspx?id=CF5FFABC-CFE1-4368-3C13-9B4FCD7C7168