無法將類型 'System.Security.Principal.WindowsIdentity' 的物件轉換為類型 'System.Web.Security.FormsIdentity'。
private void Login_Click(Object sender, EventArgs e)
{
// Create a custom FormsAuthenticationTicket containing // application specific data for the user.
string username = UserNameTextBox.Text;
string password = UserPassTextBox.Text;
bool isPersistent = false;
//若要使用Membership須設定連接的DB,會去驗證username及password是否為認可的帳密 if (Membership.ValidateUser(username, password))
{
string userData = "ApplicationSpecific data for this user.";
//建立FormsAuthenticationTicket ,表示表單驗證用它來識別已驗證的使用者的驗證票證 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket. string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie. Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
// Redirect back to original URL. Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
else {
Msg.Text = "Login failed. Please check your user name and password and try again.";
}
}
在建立FormsAuthenticationTicket成功時,表示使用者為已驗證的狀態, if(User.Identity.IsAuthenticated)
{
Response.Write("您現在是已登入狀態。");
}
//strUsername可為任意字串, 一般為使用者帳號FormsAuthentication.RedirectFromLoginPage(strUsername,false);
<authentication mode="Forms"> <forms loginUrl="login.aspx" name=".rmau"
slidingExpiration="true"
timeout="4" /></authentication><authorization> <deny users="?"/></authorization>
FormsAuthentication 類別有提到"表單驗證的啟用方法是:將 authentication 組態項目的 mode 屬性設定為 Forms。您可以要求所有應用程式的要求都包含有效的使用者驗證票證,方法是:使用 authorization 組態項目,以拒絕任何未知使用者的要求"FormsAuthenticationTicket ticket = ((FormsIdentity)Context.User.Identity).Ticket;