微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – 跟踪登录用户

我正在创建一个ASP.NET MVC应用程序.由于复杂的授权,我正在尝试构建自己的登录系统.我没有使用ASP.NET成员资格提供程序和相关的类)

我可以使用散列密码在数据库中创建新帐户.

如何跟踪用户是否已登录

生成一个长的随机数并将其与userID放在数据库和cookie中吗?

解决方法

验证用户凭据后,您可以使用以下代码
public void SignIn(string userName,bool createPersistentCookie)
{
    int timeout = createPersistentCookie ? 43200 : 30; //43200 = 1 month
    var ticket = new FormsAuthenticationTicket(userName,createPersistentCookie,timeout);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
    HttpContext.Current.Response.Cookies.Add(cookie);
}

所以你的代码可以是这样的:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult logon(string userName,string passwd,bool rememberMe)
{
    //Validatelogon is your code for validating user credentials
    if (!Validatelogon(userName,passwd))
    {
        //Show error message,invalid login,etc.
        //return View(someviewmodelHere);
    }

    SignIn(userName,rememberMe);

    return RedirectToAction("Home","Index");
}

在来自登录用户的后续请求中,HttpContext.User.Identity.Name应包含登录用户用户名.

问候!

原文地址:https://www.jb51.cc/aspnet/247173.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐