繁体   English   中英

MVC5从登录到Web应用程序的用户获取用户ID

[英]MVC5 Getting UserID from the user that's logged on to a web application

我以前编码过MVC4应用程序,现在我将其升级到MVC5。 我不知道可以使用哪种方法将当前登录到我的应用程序的用户的ID分配给UserID,我需要分配它,以便在用户创建“票证”时可以保存信息

在MVC4中,我使用了UserID = (int)WebSecurity.CurrentUserId

   public ActionResult Create([Bind(Include = "TicketID,Issue,IssuedTo,Author,Priority,CategoryID,UserID")] TicketVM model)
    {
        if (!ModelState.IsValid)
        {
            ConfigureViewModel(model);
            return View(model);
        }
        Ticket ticket = new Ticket
        {
            UserID = (int)WebSecurity.CurrentUserId, <-- ERROR
            Issue = model.Issue,
            IssuedTo = model.IssuedTo,
            CategoryID = model.CategoryID,
            Priority = model.Priority
        };
        db.Tickets.Add(ticket);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

我用

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext()
    .GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId());

为了获得当前的ApplicationUser,当我需要ID时,我通常也需要该用户。

编辑:我会尝试->

Ticket ticket = new Ticket();

ticket.UserId = Convert.ToInt32(User.Identity.GetUserId());
ticket.OtherVariables = ...;

答案是上面的代码,但是我很确定通过将(int)替换为Convert.ToInt32(...)或Int32.TryParse(...),即使对您的代码也可以使用

您不能将(int)与字符串一起使用。

您可以在Controller上使用: User.Identity.GetUserId()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM