2

目标

认证成功后获取用户信息。

问题

看看下面的代码片段:

[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public ActionResult Authenticate(User userModel)
{
    if (ModelState.IsValid)
    {
        if (userModel.IsValid(userModel.Email, userModel.Password))
        {
            FormsAuthentication
                .SetAuthCookie(userModel.Email, userModel.Remember);
            return RedirectToAction("Index", "Manager");
        }
        else
        {
            ModelState.AddModelError("", "Login data is incorrect!");
        }
    }
    return RedirectToAction("Index");
}

如您所见,它是一个普通的身份验证控制器。我需要的很简单:如果陈述userModel.IsValid属实,我如何根据他发送到服务器的电子邮件获取用户信息userModel.Email

也许将电子邮件存储在会话中,并在Index方法中调用一些方法来获取(用户)信息通过参数传递给会话中的电子邮件?(我认为这不是最好的方法,因为如果 cookie 存在而 session 不存在,这里就会出现问题。)

代码聚焦

为了获取某些用户的信息,我使用了一个简单的方法:User.Invoke((string) userEmail).

知识提升

我正在使用世界上的各种应用程序登录我的email网站password。随着email用户输入,我试图从数据库中获取他的信息。所以我问:这是最好的方法吗?也许不是更好地首先通过他的电子邮件获取用户的ID,然后选择他的信息?

我已经尝试过的

Authenticate方法中(和我之前传递的一样),我实现了以下代码:

[...]
public ActionResult Authenticate(User userModel)
    [...]
    if (userModel.IsValid(userModel, userModel.Password))
    {
        FormsAuthentication
            .SetAuthCookie(userModel.Email, userModel.Remember);

        Session["UserEmail"] = userModel.Email; // <-- Pay attention to this

        return RedirectToAction("Index", "Manager");
    }
    [...]
}

然后,在Index方法中:

public ActionResult Index()
{
    if(Request.IsAuthenticated())
    {
        UserProfile user = User.Invoke(Session["UserEmail"]));
        return View(user);
    }
    else
    {
        return View();
    }
}

但正如我所说,如果标记用户登录的 cookie 是活动的,而 session 不是,那么这里就会出现问题——一种概念冲突(cookie 与 session)。

我能做些什么?

4

1 回答 1

2

接受的答案(来自与 OP 的讨论)是:检索表单身份验证模块设置的用户名的最直接方法是使用

HttpContext.Current.User.Identity.Name

要不就

this.User.Identity.Name

在控制器中。

于 2013-08-15T18:44:08.560 回答