咨询电话:186 7916 6165 咨询电话:186 7916 6165 (微信同号)    在线QQ:181796286
NEWS BLOG ·
学无止境
关注开优网络 关注前沿
ASP.NET+jQuery上传头像
ASP.NET页面中用javascript响应文本框的回车事件

ASP.NET Web 开发之验证机制

发表日期:2015-09-10    文章编辑:南昌开优网络    浏览次数:3800    标签:ASP.NET应用

一、ASP.NET票据验证
1、在根目录建立一个Global.asax文件,烤入一段代码
protected void Application_AuthenticateRequest(object SENDER, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket tiecket = id.Ticket;
string userData = tiecket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
}
}


2、在web.config 文件中配置目录权限及登录页,登录页,在system.web节点中
//mode="Forms"指采用表单验证, 
        //name指名称, 
        //loginUrl转到的url, 
        //protection所有页面         //path路径/根目录
 <authentication mode="Forms">
      <forms name="mycook" loginUrl="login_direct.aspx" protection="All" path="/" />
 </authentication>

loginUrl="login_direct.aspx"代码如下: 直接写在page_load中
 string strReturnURL = Request.Params["ReturnUrl"];
            if (strReturnURL.Contains("admin"))
            {
                Response.Redirect("admin/login.aspx?ReturnURL=default.aspx");
            }
           else if (strReturnURL != null && strReturnURL.Contains("admin"))
            {
                Response.Redirect("admin/login.aspx?ReturnURL=" + strReturnURL);
            }
            else
            {
                Response.Redirect("index.aspx?ReturnURL=" + strReturnURL);
            }


3、配置目录权限,在system.web节点外面
    //path路径,authorization授权,allow允许,roles角色,deny拒绝  
第一段代码 admin目录只授权于admin角色拒绝所有的用户
第二段代码 user目录只授权于user角色拒绝所有的用户
第三段代码 admin/login.aspx文件允许所有用户打开如该文件有图片及样式应再加上images和css或js文件夹也允许所有用户打开
<location path="admin">
    <system.web>
      <authorization>
        <allow roles="admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="admin/login.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="admin/css">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>  
  <location path="admin/images">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="user">//路径
    <system.web>
      <authorization>
        <allow roles="user"/>//角色
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>  

4、在登录页的登录事件中的登录成功后烤入一段代码,如登录到user中心则采用user角色
 
 HttpCookie cook;
                string strReturnURL; //登录成功后返回的URL
                string roles = "user";  //用户角色
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1, name, DateTime.Now, DateTime.Now.AddMinutes(30), false, roles);
                cook = new HttpCookie("mycook");
                cook.Value = FormsAuthentication.Encrypt(ticket);
                Response.Cookies.Add(cook);
                strReturnURL = Request.Params["ReturnUrl"];
                if (strReturnURL != null && strReturnURL.Contains(".aspx"))
                {
                    Response.Redirect(strReturnURL);
                }
                else
                {
                    Response.Redirect("user/index.aspx");
                }
//获取登录的用户名
litusername.Text = User.Identity.Name;
<%=User.Identity.Name %>
//通过登录的用户名获取Model
Model.User model = udao.GetModel(User.Identity.Name);
//退出
FormsAuthentication.SignOut();
//判断是否登录
if (!User.Identity.IsAuthenticated)
{
Utility.Tool.Alert("请先登录", this.Page);
return;
}

5、登录
LoginView         登录控件 注:以下都是放在LoginView控件中
AnonymousTemplate节点登录时的样式
LoggedInTemplate节点登录后的样式
LoginName登录后显示的用户名控件
LoginStatus登录后退出的控件
用一个LoginView控件包括起来< AnonymousTemplate>登录时状态< LoggedInTemplate>登录后状态

找到LoginView控件中的TextBox
txtname.Text=(LoginView1.FindCoutrol("txtname")as TextBox).Text.Trim();



二、用户自定义验证  
子目录或虚似目录的访问 如http://www.cxlook.com/bbs/default.aspx 或http://bbs.cxlook.com/default.aspx
1、在web.config中的system.web节点上面(外)加上:
 <appSettings>
    <add key="bbsroot" value="/bbs/" />
  </appSettings>
2、指定到bbsroot
string root = System.Configuration.ConfigurationManager.AppSettings["bbsroot"];
3、项目中的Web层右键属性虚似路径  /bbs/
4、登录事件
Model.User model = new DAL.UserDAL().LoginByUserName(name, pwd);
if (model == null)
{
model = new DAL.UserDAL().LoginByEmail(name, pwd);
}
if (model == null)
{
Utility.Tool.Alert("用户名或密码错误", this.Page);
return;
}
Session["user"] = model;

5、创建ValidatorPage.cs类文件  所有user文件夹下所有文件都要继承该类即 System.Web.UI.Page 改为 ValidatorPage
public class ValidatorPage : System.Web.UI.Page
    {
        //pageunload事件,并不是指浏览器关闭,而是指页面关闭,所以刷新的时候,依然会执行以下事件
        protected void Page_Unload(object sender, EventArgs e)
        {

        }
        //虚似目录名称
        string root = System.Configuration.ConfigurationManager.AppSettings["bbsroot"];
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            if (Session["user"] == null)
            {
                //这里写跳转到登陆页面例如: 
                Response.Redirect(string.Format(root + "/login.aspx?page={0}", Request.Path));
            }            
        }
    }
5.1后台管理文件夹admin在所有页面中加上
string root = System.Configuration.ConfigurationManager.AppSettings["bbsroot"];

if (Session["admin"] == null)
{
    Response.Redirect(string.Format(root + "admin/login.aspx?page={0}", Request.Url));
}

6、在所有登录到user的登录事件中的Session["user"] = model;后面加上自动转向
string page = Request.QueryString["page"];
if (string.IsNullOrEmpty(page))
{
Response.Redirect(root + "user/");
}
else
{
Response.Redirect(page);
}

关闭窗口时退出登录并计算时间
1、在Globl.asax中的Session_End节点中加上7方法
2、在web.config中的<system.web>节点中加上
<sessionState mode="InProc" timeout="20"/>

7、计算用户在线时间 在Global全局处理程序中的Session_End节点中加上
 if (Session["user"] != null)
            {
                #region 记录在线时间
                Model.User u = Session["user"] as Model.User;
                DateTime now = DateTime.Now;
                new DAL.LogDAL().Add(new Model.Log()
                {
                    username = u.username,
                    ip = Request.UserHostAddress,
                    remark = "Session失效",
                    createdate = now
                });
                string tmp = new DAL.LogDAL().GetLastLoginDate(u.username);
                if (tmp == "")
                {
                    int t = int.Parse(Math.Round((now - u.createdate).TotalMinutes).ToString());
                }
                else
                {
                    DateTime dl = DateTime.Parse(tmp);
                    int t = int.Parse(Math.Round((now - dl).TotalMinutes).ToString());
                    new DAL.UserDAL().UpdateOnLineTime(u.id, t);
                }
                #endregion
            }
    在DAL层中LogDAL.cs中加上获取最后登录的时间   
 public string GetLastLoginDate(string username)
        {
            string sql = "select top 1 createdate from bbs_log where username=@username and remark='登录' order by createdate desc";
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand(sql);
            db.AddInParameter(dbCommand, "username", DbType.String, username);
            object obj = db.ExecuteScalar(dbCommand);
            if (obj == null || obj.ToString() == "")
            {
                return "";
            }
            return DateTime.Parse(obj.ToString()).ToString("yyyy-MM-dd HH:mm");
        }

8、在所有登录事件Session["user"] = model;之前加上日志代码
new DAL.LogDAL().Add(new Model.Log()
            {
                ip = Request.UserHostAddress,
                remark = "登录",
                username = name,
            });

9、在所有退出登录事件中Session["user"] = null;之前加上
DateTime now = DateTime.Now;
new DAL.LogDAL().Add(new Model.Log()
{
username = u.username,
ip = Request.UserHostAddress,
remark = "退出",
createdate = now
});
string tmp = new DAL.LogDAL().GetLastLoginDate(u.username);
if (tmp == "")
{
int t = int.Parse(Math.Round((now - u.createdate).TotalMinutes).ToString());
}
else
{
DateTime dl = DateTime.Parse(tmp);
int t = int.Parse(Math.Round((now - dl).TotalMinutes).ToString());
new DAL.UserDAL().UpdateOnLineTime(u.id, t);
}

//在母版页中的退出并记录在线时间
//退出登录
protected void LinkButton1_Click(object sender, EventArgs e)
{
Model.User model = Session["user"] as Model.User;

List<string> list = Application["online"] as List<string>;
if (list.Contains(model.username))
{
list.Remove(model.username);
}
Application.Lock();
Application["online"] = list;
Application.UnLock();

#region 写日志并计算在线时间
DAL.LogDAL ldal = new Xiaobin.BBS.DAL.LogDAL();
DateTime now = DateTime.Now;
ldal.Add(new Xiaobin.BBS.Model.Log()
{
username = model.username,
remark = "退出",
ip = Request.UserHostAddress,
createdate = now
});

//取最近一次登录时间
DAL.UserDAL udal = new Xiaobin.BBS.DAL.UserDAL();
string tmp = ldal.GetLastLoginDate(model.username);
if (tmp == "")
{
//用户之前没有登录过,则以注册时间为登录时间来计算
int t = int.Parse(Math.Round((now - model.createdate).TotalMinutes).ToString());
udal.UpdateOnlineTime(model.id, t);
}
else
{
DateTime d1 = DateTime.Parse(tmp);
int t = int.Parse(Math.Round((now - d1).TotalMinutes).ToString());
udal.UpdateOnlineTime(model.id, t);
}
#endregion

Session["user"] = null;

Response.Redirect(root + "login.aspx");
}

在UserDAL.cs中加上更新onlinetime字段方法
public void UpdateOnlineTime(int id, int t)
{
string sql = "update bbs_user set onlinetime=onlinetime+" + t + " where id=" + id;
Database db = DatabaseFactory.CreateDatabase();
db.ExecuteNonQuery(CommandType.Text, sql);
}






10、获取所有登录用户信息 在Global全局处理程序中的Application_Start节点中加上
if (Application["online"] == null)
{
List<string> list = new List<string>();
Application["online"] = list;
}

11、在所有登录事件写日志之前加上
List<string> list = Application["online"] as List<string>;
if (!list.Contains(model.username))
{
list.Add(model.username);
}
Application.Lock();
Application["online"] = list;
Application.UnLock();

12、在所有退出事件写日志之前加上
List<string> list = Application["online"] as List<string>;
if (!list.Contains(u.username))
{
list.Remove(u.username);
}
Application.Lock();
Application["online"] = list;
Application.UnLock();