Mar*_*ark 38 c# asp.net cookies forms-authentication
我正在创建一个cookie并在成功登录后存储用户名的值.如何在网站打开时访问cookie.如果cookie存在,我想填写cookie值的用户名文本框.以及如何解密该值以获取用户名.我通过从数据库获取用户详细信息来进行服务器端验证.我正在使用vs 2010与c#
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddYears(1), chk_Rememberme.Checked, "User Email");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chk_Rememberme.Checked)
{
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
}
Run Code Online (Sandbox Code Playgroud)
创建cookie,名称为.YAFNET_Authentication,内容已加密
Webconfig:
<forms name=".YAFNET_Authentication" loginUrl="Home.aspx"
protection="All" timeout="15000" cookieless="UseCookies"/>
Run Code Online (Sandbox Code Playgroud)
ada*_*ost 84
您可以使用Request.Cookies集合来读取cookie.
if(Request.Cookies["key"]!=null)
{
var value=Request.Cookies["key"].Value;
}
Run Code Online (Sandbox Code Playgroud)
kvc*_*kvc 21
FormsAuthentication.Decrypt获取cookie的实际值,而不是它的名称.您可以获得cookie值
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
Run Code Online (Sandbox Code Playgroud)
并解密.
小智 8
将此函数添加到您的global.asax
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (authCookie == null)
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
if (authTicket == null)
{
return;
}
string[] roles = authTicket.UserData.Split(new char[] { '|' });
FormsIdentity id = new FormsIdentity(authTicket);
GenericPrincipal principal = new GenericPrincipal(id, roles);
Context.User = principal;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用HttpContext.Current.User.Identity.Name来获取用户名.希望能帮助到你
| 归档时间: |
|
| 查看次数: |
140974 次 |
| 最近记录: |