惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
Microsoft Security Blog
Microsoft Security Blog
Recent Announcements
Recent Announcements
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
罗磊的独立博客
腾讯CDC
云风的 BLOG
云风的 BLOG
月光博客
月光博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
宝玉的分享
宝玉的分享
U
Unit 42
I
InfoQ
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
美团技术团队
IT之家
IT之家
Stack Overflow Blog
Stack Overflow Blog
F
Fortinet All Blogs
GbyAI
GbyAI
S
SegmentFault 最新的问题

博客园 - XXXCccddd

数据库SQL的效率 javascript去空格函数 精妙SQL语句 Session操作 Server.Transfer 和 Response.Redirect 区别 vs.net web项目使用visual source safe进行源代码管理 数据库设计规范 常用函数表 xmlhttp实现无刷新页面 XP风格样式表 Using Forms Authentication in ASP.NET - Part 2 Using Forms Authentication in ASP.NET - Part 1 如何关闭系统所有Excel进程 [转]每一项都是js中的小技巧,但十分的实用! asp.net中常用的一些小技巧 ASP.NET开发经验积累(转) Visual SourceSafe应用守则(转) 应用系统架构设计-补全篇(转) 系统设计说明书(架构、概要、详细)目录结构
在AS.net中实现单点登陆
XXXCccddd · 2005-11-24 · via 博客园 - XXXCccddd

Posted on 2005-11-24 09:28  XXXCccddd  阅读(354)  评论()    收藏  举报

实现思路

利用Cache的功能,我们把用户的登录信息保存在Cache中,并设置过期时间为Session失效的时间,因此,一旦Session失效,我们的Cache也过期;而Cache对所有的用户都可以访问,因此,用它保存用户信息比数据库来得方便。
<!--StartFragment-->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;

<!--StartFragment-->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.<a href="http://www.chinaitpower.com/Dev/Web/Asp/index.html" target="_blank">asp</a>x.cc/'>【孟宪会之精彩世界】";
    Msg.Text += "</a>,祝您浏览愉快!:)</h4>";
  }
  else
  {
    // 在 Cache 中发现该用户的记录,表名已经登录过,禁止再次登录
    Msg.Text="<h4 style='color:red'>抱歉,您好像已经登录了呀:-(</h4>";
   return;
  }
}