TykiMikk
TykiMikk

Reputation: 1068

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

I previously coded a MVC4 application and now I'm upgrading it to MVC5. I don't know what method I can use to assign the id of the user that's currently logged on to my application to UserID, I need it assigned so that I can save the information when the User creates a "Ticket"

In MVC4 I used 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");
    }

Upvotes: 1

Views: 261

Answers (2)

iamanoob
iamanoob

Reputation: 208

I use

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

To get the current ApplicationUser, when i need the ID i usually need the user too so..

Edit : I would try to do ->

Ticket ticket = new Ticket();

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

The answer is the above code but i'm pretty sure it would of worked even with your code by replacing (int) into Convert.ToInt32(...) or Int32.TryParse(...)

you can't use (int) with a string.

Upvotes: 3

Ricardo Fran&#231;a
Ricardo Fran&#231;a

Reputation: 3003

You can use on Controller: User.Identity.GetUserId()

Upvotes: 1

Related Questions