我为什么总是不能跳过登录界面?
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version txtUserName.Text, // user name DateTime.Now, // creation DateTime.Now.AddMinutes(60),// Expiration true, // Persistent roles );
,我把Persistent想改为true,也不行,谁能解答?
你在Config中配置了吗?以下摘自MSDN
配置 ASP.NET 身份验证支持。该元素只能在计算机、站点或应用程序级别声明。如果试图在配置文件中的子目录或页级别上进行声明,则将产生分析器错误信息。
<configuration> <system.web> <authentication>
<authentication mode="Windows|Forms|Passport|None">
<forms name="name"
loginUrl="url"
protection="All|None|Encryption|Validation"
timeout="30" path="/" >
requireSSL="true|false"
slidingExpiration="true|false">
<credentials passwordFormat="Clear|SHA1|MD5">
<user name="username" password="password"/>
</credentials>
</forms>
<passport redirectUrl="internal"/>
</authentication>
必选属性
属性
选项
说明
mode
控制应用程序的默认身份验证模式。
Windows
将 Windows 验证指定为默认的身份验证模式。当使用以下任意形式的 Microsoft Internet 信息服务 (IIS) 身份验证时使用该模式:基本、简要、集成的 Windows 验证 (NTLM/Kerberos) 或证书。
Forms
将 ASP.NET 基于窗体的身份验证指定为默认的身份验证模式。
Passport
将 Microsoft Passport 身份验证指定为默认的身份验证模式。
None
不指定任何身份验证。只有匿名用户是预期的或者应用程序可以处理事件以提供其自身的身份验证。
子标记
<forms>
为基于窗体的自定义身份验证配置 ASP.NET 应用程序。
<passport>
指定要重定向到的页(如果该页要求身份验证,而用户尚未通过 Passport 注册)。
示例
以下示例为基于窗体的身份验证配置站点,指定传输来自客户端的登录信息的 Cookie 的名称,并指定当初始身份验证失败时所使用的登录页的名称。必须将 <authorization> 节包含在内才能要求所有用户进行 Forms 身份验证,并且拒绝对站点的所有匿名用户访问。
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="401kApp" loginUrl="/login.aspx"/>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
MSDN上面的例子有点小问题.他存储用户登录信息是用加密Cookies来做的.需要以下地方修改代码:
private void Button1_Click(object sender, System.EventArgs e) { bool isAuthenticated = IsAuthenticated( txtUserName.Text,txtPassword.Text ); if (isAuthenticated == true ) { string roles = GetRoles( txtUserName.Text, txtPassword.Text ); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version txtUserName.Text, // user name DateTime.Now, // creation DateTime.Now.AddMinutes(60),// Expiration false, // Persistent roles ); // User data
string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted ticket to the // cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);//MSDN上面没有写这一句,加上就可以了!
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUserName.Text, false )); } }
我已经将修改好的例子上传,你可以参照一下!