您现在的位置是:网站首页> 编程资料编程资料
ASP.NET Forms身份认证_实用技巧_
2023-05-24
319人已围观
简介 ASP.NET Forms身份认证_实用技巧_
asp.net程序开发,用户根据角色访问对应页面以及功能。
项目结构如下图:

根目录 Web.config 代码:
admin文件夹中 Web.config 代码:
teacher文件夹中 Web.config 代码:
student文件夹中 Web.config 代码:
Login.aspx中登录成功后设置Cookie,设置Cookie代码:
protected void SetLoginCookie(string username, string roles) { System.Web.Security.FormsAuthentication.SetAuthCookie(username, false); System.Web.Security.FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddDays(1), false, roles, "/"); string hashTicket = FormsAuthentication.Encrypt(ticket); HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket); HttpContext.Current.Response.SetCookie(userCookie); }Global.asax 中进行身份验证:
protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; HttpContext ctx = app.Context; //获取本次Http请求的HttpContext对象 if (ctx.User != null) { if (ctx.Request.IsAuthenticated == true) //验证过的一般用户才能进行角色验证 { System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity)ctx.User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket; //取得身份验证票 string userData = ticket.UserData;//从UserData中恢复role信息 string[] roles = userData.Split(','); //将角色数据转成字符串数组,得到相关的角色信息 ctx.User = new System.Security.Principal.GenericPrincipal(fi, roles); //这样当前用户就拥有角色信息了 } } }以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
相关内容
- asp.net实现服务器文件下载到本地的方法_实用技巧_
- Asp.net MVC利用knockoutjs实现登陆并记录用户的内外网IP及所在城市(推荐)_实用技巧_
- Redis缓存详解_实用技巧_
- webapi中如何使用依赖注入_实用技巧_
- .NET MD5加密解密代码解析_实用技巧_
- .NET发布网站详细步骤_实用技巧_
- 详解在ASP.NET Core下使用SignalR技术_实用技巧_
- 利用Typings为Visual Studio Code实现智能提示功能_实用技巧_
- .NET客户端实现Redis中的管道(PipeLine)与事物(Transactions)_实用技巧_
- Json日期格式问题的四种解决方法(超详细)_实用技巧_
