栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#中FormsAuthentication用法实例

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#中FormsAuthentication用法实例

using System;
using System.Web;
using System.Web.Security;

namespace AuthTest
{
  public class Authentication
  {
    /// 
    /// 设置用户登陆成功凭据(cookie存储)
    /// 
    /// 用户名
    /// 密码
    /// 权限
    public static void Setcookie(string UserName,string PassWord,string Rights)
    {
      //
      //String PassWord="test";
      //
      String UserData = UserName + "#" + PassWord+"#"+Rights;
      if (true)
      {
 //数据放入ticket
 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddMinutes(60), false, UserData);
 //数据加密
 string enyTicket = FormsAuthentication.Encrypt(ticket);
 Httpcookie cookie = new Httpcookie(FormsAuthentication.FormscookieName, enyTicket);
 HttpContext.Current.Response.cookies.Add(cookie);
      }
    }
    /// 
    /// 判断用户是否登陆
    /// 
    /// True,Fales
    public static bool isLogin()
    {
      return HttpContext.Current.User.Identity.IsAuthenticated;
    }
    /// 
    /// 注销登陆
    /// 
    public static void logOut()
    {
      FormsAuthentication.SignOut();
    }
    /// 
    /// 获取凭据中的用户名
    /// 
    /// 用户名
    public static string getUserName()
    {
      if (isLogin())
      {
 string strUserData = ((FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData;
 string[] UserData = strUserData.Split('#');
 if (UserData.Length != 0)
 {
   return UserData[0].ToString();
 }
 else
 {
   return "";
 }
      }
      else
      {
 return "";
      }
    }
    /// 
    /// 获取凭据中的密码
    /// 
    /// 密码
    public static string getPassWord()
    {
      if (isLogin())
      {
 string strUserData = ((FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData;
 string[] UserData = strUserData.Split('#');
 if (UserData.Length!=0)
 {
   return UserData[1].ToString();
 }
 else
 {
   return "";
 }
      }
      else
      {
 return "";
      }
    }
    /// 
    /// 获取凭据中的用户权限
    /// 
    /// 用户权限
    public static string getRights()
    {
      if (isLogin())
      {
 string strUserData = ((FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData;
 string[] UserData = strUserData.Split('#');
 if (UserData.Length!=0)
 {
   return UserData[2].ToString();
 }
 else
 {
   return "";
 }
      }
      else
      {
 return "";
      }
    }
  }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/125690.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号