如何获取已登录用户的ID? - ASP.NET MVC [英] How Can I get the id of logged user? - ASP.NET MVC

查看:410
本文介绍了如何获取已登录用户的ID? - ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。这是我的登录控制器:



Hi. Here is my login controller:

public ActionResult Login(Login login)
{
    if (ModelState.IsValid)
    {
        if (new AllFictionMembershipProvider().ValidateUser(login.Email, Criptografia.Encriptar(login.Senha)))
        {
            FormsAuthentication.SetAuthCookie(login.Email, false);

            return RedirectToDefault();

        }
    }

    ModelState.AddModelError("Erro", "Login ou senha incorretos!");
    return View(login);
}





我正在考虑创建一个会话,在登录后保存用户的ID,因为我需要在另一个控制器中访问它,进行插入。我该怎么办?



I am thinking in creating a session that saves the id of the user after his login, because I need to access it in another controller, to make an insert. How Can I do it?

推荐答案

当您使用此ActionResult时,您正在传递登录模型,如同用户名/电子邮件和密码一样。其中,至少用户名/电子邮件应该是唯一的。因此,在这些独特的属性中,使用Unique属性从数据库中检索用户ID,例如



上下文方法LINQ将如下:

When you are using this ActionResult, you are passing the Login Model, as in Username/Email and Password oviously. Out of these, atleast the Username/Email should be unique. So, out of these unique property, retreive the User Id from the database using the Unique property like

The context method LINQ would go like:
var userID = Context.USER.Where(user=>user.UserName == login.userName).select(user=>user.UserID);





这里我考虑过,UserName作为Unique属性,使用服务中的上下文方法而不是控制器。

然后将UserID存储在像



Here I have considered, UserName as the Unique property, use the context method in the Service not in the controller.
Then Store the UserID in a session like

Session["UserID"] = userID;
var idToBeUsedForInsert = Convert.ToInt32(Session["UserID"]);



然后尝试将Session解析为int,然后使用该ID插入数据库。

希望你能从中得到一些想法,否则请回复你对你的疑问的评论。

谢谢

:)


Then try parse the Session into int and Then user the ID to insert into the database.
Hope you get some idea from this, else please post back your comments regarding your queries.
Thanks
:)


这篇关于如何获取已登录用户的ID? - ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆