using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;
namespace WebApplication3
{
/// <summary>
/// WebForm1 的摘要说明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.TextBox TextBoxUser;
protected System.Web.UI.WebControls.TextBox TextBoxPassword;
protected System.Web.UI.WebControls.Button Button1;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}

//此方法用来验证用户合法性的
private bool Confirm(string user,string password)
{
if(user=="lihongge" || password=="lihongge")
return true;
else
return false;
}
//此方法用来获得的用户对应的所有的role用逗号分割的一个字符串
private string UserToRole(string user)
{
if(user=="lihongge")
return "admin";
else
return "guest";
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{    
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load); }
#endregion private void Button1_Click(object sender, System.EventArgs e)
{
string user = TextBoxUser.Text; //读取用户名
string password = TextBoxPassword.Text; //读取密码
if(Confirm(user,password) == true) //confirm方法用来验证用户合法性的
{
string userRoles = UserToRole(user); //调用UserToRole方法来获取role字符串
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1,user,DateTime.Now,DateTime.Now.AddMinutes(30), false,userRoles,"/") ; //建立身份验证票对象
string HashTicket = FormsAuthentication.Encrypt (Ticket) ; //加密序列化验证票为字符串
HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket) ; 
//生成Cookie
Context.Response.Cookies.Add (UserCookie) ; //输出Cookie
Context.Response.Redirect("login.aspx") ; // 重定向到用户申请的初始页面
}
else
{
Label1.Text="用户名,密码错误";
}
}
}
}编译器没有错误,但文件夹没有生成成功COOKIES

解决方案 »

  1.   

    FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1,user,DateTime.Now,DateTime.Now.AddMinutes(30), false,userRoles,"/") ; //建立身份验证票对象
    可以改成FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1,user,DateTime.Now,DateTime.Now.AddMinutes(30), true,userRoles,"/") ; //建立身份验证票
    试一下,这个参数的意义是是否保证Cookie的持久性。
    如果不行的话,可以检查一下你的IE设置。
      

  2.   

    如果WEB.CONFIG文件中的验证模式是WINDOWS,不是FORMS,用这语句能生成COOKIES吗?