MVC5会员提供商GetUserId()

时间:2015-03-26 02:29:14

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我在这上面看过类似的帖子,但没有人给我一个我可以真正开始工作的答案。

我修改了AuthConfig.cs文件以允许OAuth注册。

我肯定已登录并获得授权,但仍然无法检索UserId。

    public ActionResult Index()
    {
        var isAuthenticated = User.Identity.IsAuthenticated; // returns true
        var userName = User.Identity.GetUserName(); // returns rory
        var userId = User.Identity.GetUserId(); // returns null

        return View();
    }

为什么这会一直返回null?我以前曾多次在其他项目中使用它,从未遇到过问题。想法?

2 个答案:

答案 0 :(得分:0)

使用以下检索Id的方式,而问题中的方法不能。我之前没有见过这个,也没有在其他任何答案中看到它。

WebSecurity.GetUserId(User.Identity.Name);

成功返回UserId,无论它是OAuth还是本地帐户。

答案 1 :(得分:0)

var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;