gpt4 book ai didi

c# - MVC5 从登录到 Web 应用程序的用户那里获取 UserID

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:13 24 4
gpt4 key购买 nike

我之前编写了一个 MVC4 应用程序,现在我要将它升级到 MVC5。我不知道我可以使用什么方法将当前登录到我的应用程序的用户的 ID 分配给 UserID,我需要分配它以便在用户创建“Ticket”时保存信息

在 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) 与字符串一起使用。

关于c# - MVC5 从登录到 Web 应用程序的用户那里获取 UserID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36322841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com