如何访问用户注册时给出的“名称”

时间:2012-12-19 09:53:51

标签: c# asp.net-mvc-3 login

所以我只希望允许登录用户为自己预订假期。我认为最简单的方法是在person表中比较登录用户的'name''name'。所以....

public ActionResult Create()
    {
        string xx = (string)Session["usernameID"];
        int? currentPersonID = Convert.ToInt32(xx);

        string userNameComparedAgainstLoginName = // here is where i want to say 'name' of logged in user

        CreateModel model = new CreateModel();
        model.currentPersonID = currentPersonID.Value;
        model.PList4DD = db.People.ToList();


        if (userNameComparedAgainstLoginName == model.userName)
        {
            ViewBag.Id = new SelectList(db.People, "Id", "Name");
            return View(model);
        }
        else
        {
            TempData["canOnlyBookHolidaysForYourself"] = "I'm afraid you can only book holidays for yourself";
            return RedirectToAction("Index");
        }
    }

用户注册时给出的名称与db中使用的名称相同。

那么有人可以告诉我如何访问登录的“名称”吗?

由于

2 个答案:

答案 0 :(得分:4)

在会话中存储记录的用户数据(例如用户名/电子邮件/ ID)是不好的做法。 好的做法是创建自定义用户主体或标识,并将应用程序中经常使用的所有用户数据存储在其中。

您最好创建自定义主体或身份,并将该信息存储在身份验证Cookie中,并通过User.Identity.XXX访问它

这是一个链接,其中详细描述了如何创建自定义主体。 ASP.NET MVC - Set custom IIdentity or IPrincipal

或者,如果您不需要这样复杂的机制,您只需使用HttpContext中的默认User.Identity。

祝你好运!

答案 1 :(得分:1)

您可以从User.Identity

获取名称

您只需使用User.Identity.Name

即可