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应包含登录用户用户名.

问候!

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....