C#学习教程:在asp.netweb应用程序中进行身份验证时遇到问题我使用本教程作为指南,它几乎准确地解释了我想要做什么,但是当我输入我的用户名和密码时,身份验证不起作用。请允许我解释一下。这是我的HTML的相关部分。没什么异常:该页面包含用户名和登录按钮(以及用于记住cookie的复选框,但我认为这与我的问题无关)。这是后面的代码:usingSystem;使用System.Collections.Generic;使用System.Linq;使用System.Web;使用System.Web.UI;使用System.Web.UI.WebControls;使用System.Data.SqlClient;使用System.Web.Security;namespaceMRAApplication{publicpartialclass_1__0__0__0_LoginScreen:System.Web.UI.Page{protectedvoidPage_Load(objectsender,EventArgse){this.cmdLogin.ServerClick+=newSystem.EventHandler(this.cmdLogin_ServerClick);}privateboolValidateUser(stringuserName,stringpassWord){SqlConnectionconn;SqlCommand命令;字符串lookupPassword=null;//检查无效的用户名。//userName不能为null,并且必须介于1到15个字符之间。if((null==userName)||(0==userName.Length)||(userName.Length>15)){System.Diagnostics.Trace.WriteLine("[ValidateUser]用户名输入验证失败。");返回假;}//检查无效密码。//passWord不能为null,并且必须介于1到25个字符之间。如果((null==passWord)||(0==passWord.Length)||(passWord.Length>25)){System.Diagnostics.Trace.WriteLine("[ValidateUser]输入密码验证失败。");返回假;}try{//咨询您的SQLServer管理员以获取适当的连接//用于连接到本地SQLServer的字符串。conn=newSqlConnection("数据库连接");conn.Open();//创建SqlCommand以在给定提供的用户名的情况下从用户表中选择pwd字段。cmd=newSqlCommand("SelectPasswordfromUserswhereUser=@userName",conn);cmd.Parameters.Add("@userName",System.Data.SqlDbType.VarChar,25);cmd.Parameters["@userName"].Value=userName;//执行命令并将pwd字段提取到lookupPassword字符串中。lookupPassword=(string)cmd.ExecuteScalar();//清理命令和连接对象。cmd.Dispose();conn.Dispose();}catch(Exceptionex){//为调试添加错误处理。//此错误消息不应发送回t他来电者。System.Diagnostics.Trace.WriteLine([ValidateUser]Exception"+ex.Message);}//如果没有找到密码,返回false。if(null==lookupPassword){//您可以在此处将失败的登录尝试写入事件日志以提高安全性。返回假;}//比较lookupPassword和inputpassWord,使用区分大小写的比较。return(0==string.Compare(lookupPassword,passWord,false));}privatevoidcmdLogin_ServerClick(objectsender,System.EventArgse){if(ValidateUser(txtUserName.Value,txtUserPass.Value)){FormsAuthenticationTickettkt;字符串cookiestr;HttpCookieck;tkt=newFormsAuthenticationTicket(1,txtUserName.Value,DateTime.Now,DateTime.Now.AddMinutes(30),chkPersistCookie.Checked,"您的自定义数据");cookiestr=FormsAuthentication.Encrypt(tkt);ck=newHttpCookie(FormsAuthentication.FormsCookieName,cookiestr);如果(chkPersistCookie.Checked)ck.Expires=tkt.Expiration;ck.Path=FormsAuthentication.FormsCook即路径;Response.Cookies.Add(ck);字符串strRedirect;strRedirect=Request["ReturnUrl"];如果(strRedirect==null)strRedirect="default.aspx";Response.Redirect(strRedirect,true);}elseResponse.Redirect("1.0.0.0_LoginScreen.aspx",true);现在,我已经测试了我的连接字符串并且它可以正常工作它连接到SQLServer数据库中的一个表,该数据库具有3列用户、密码和用户角色。现在我在表中只有一个测试条目,如下所示。但是当我运行应用程序并将“test”输入“txtUserName”和“password”输入“txtUserPass”并单击“提交”时,它会重定向回登录页面,这意味着它返回false作为“if(ValidateUser(txtUserName.值,txtUserPass。值))”。如果有人可以帮助我解决这个错误,我将不胜感激。感谢您的帮助。?这是我第一次尝试身份验证,所以我不完全确定如何使用断点获取返回值。您想在连接到SQLServer之前使用硬编码的用户名和密码进行测试。protectedvoidcmdLogin_ServerClick(objectsender,System.EventArgse){if(String.Equals(txtUserName.Value,"johndoe",StringComparison.InvariantCultureIgnoreCase)&&String.Equals(txtUserPass.Value,"123456",StringComparison.InvariantCultureIg){varroles=new[]{"Administrators"};varticket=newFormsAuthenticationTicket(1,txtUserName.Value,DateTime.Now,DateTime.Now.AddMinutes(30),chkPersistCookie.Checked,string.Join(",",角色),FormsAuthentication.FormsCookiePath);varcookie=newHttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(ticket));如果(chkPersistCookie.Checked)cookie.Expires=ticket.Expiration;Response.Cookies.Add(cookie);stringreturnUrl=Request["ReturnUrl"];if(returnUrl==null)returnUrl="default.aspx";Response.Redirect(returnUrl,true);}elseResponse.Redirect("1.0.0.0_LoginScreen.aspx",true);}如何创建principal对象当为经过身份验证的用户请求页面时,您需要从cookie中检索身份验证票证,并创建Pri对象以上就是C#学习教程:在asp.netweb应用验证中遇到问题分享的全部内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注—//Global.asax.cspublicclassGlobal:HttpApplication{voidApplication_AuthenticateRequest(objectsender,EventArgse){HttpCookiedecryptedCookie=Context.Request.Cookies[FormsAuthentication.FormsCookieName];if(decryptedCookie!=null){FormsAuthenticationTicketdecryptedticket=FormsAuthentication();string[]roles=ticket.UserData.Split(new[]{","},StringSplitOptions.RemoveEmptyEntries);varidentity=newGenericIdentity(ticket.Name);varprincipal=newGenericPrincipal(身份,角色);HttpContext.Current.User=主体;Thread.CurrentPrincipal=HttpContext.Current.User;}}}用法publicpartialclass_Default:Page{protectedvoidPage_Load(objectsender,EventArgse){if(User.Identity.IsAuthenticated){stringusername=User.Identity.Name;boolisAdministrator=User.IsInRole("管理员");}}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
