Steven Yu
Steven Yu

Reputation: 155

How User.Identity.GetUserId() work in ASP.NET MVC5

As the title mentioned, I have use this method to recognize the user id in my project. Meanwhile, I have see this post also but my output still not match with the user id. (Post is > How do you use User.Identity.GetUserId();). So basically the output of user id is this

enter image description here

And my MVC 5 Controller code is

    public class OrderController : Controller
    {
        [Authorize]
        [HttpGet]
        public ActionResult PlaceOrder()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PlaceOrder(Order orderDetail)
        {
            String message = "";
            using (myDatabaseEntities1 myDatabase1 = new myDatabaseEntities1())
            {
                orderDetail.User_ID = Convert.ToInt32(User.Identity.GetUserId());
                orderDetail.OrderDate = System.DateTime.Now;

                //WF
                Double PriceOfF1 = Convert.ToDouble(orderDetail.A_ChickenChop_BP.GetValueOrDefault()) * 14.9;
                Double PriceOfF2 = Convert.ToDouble(orderDetail.A_ChickenChop_M.GetValueOrDefault()) * 14.9;
                Double PriceOfF3 = Convert.ToDouble(orderDetail.A_Spaghetti_AH.GetValueOrDefault()) * 10.9;
                Double PriceOfF4 = Convert.ToDouble(orderDetail.A_Spaghetti_P.GetValueOrDefault()) * 10.9;
                Double PriceOfF5 = Convert.ToDouble(orderDetail.A_Spaghetti_S.GetValueOrDefault()) * 10.9;
                //CF
                Double PriceOfF6 = Convert.ToDouble(orderDetail.A_ChickenRice_CB.GetValueOrDefault()) * 6.9;
                Double PriceOfF7 = Convert.ToDouble(orderDetail.A_ChickenRice_CW.GetValueOrDefault()) * 6.9;
                Double PriceOfF8 = Convert.ToDouble(orderDetail.A_ChickenRice_D.GetValueOrDefault()) * 6.9;
                Double PriceOfF9 = Convert.ToDouble(orderDetail.A_WantanMee_NS.GetValueOrDefault()) * 6.9;
                Double PriceOfF10 = Convert.ToDouble(orderDetail.A_WantanMee_IS.GetValueOrDefault()) * 6.9;

                Double T_Price = orderDetail.OrderPrice;

                T_Price = PriceOfF1 + PriceOfF2 + PriceOfF3 + PriceOfF4 + PriceOfF5 +
                    PriceOfF6 + PriceOfF7 + PriceOfF8 + PriceOfF9 + PriceOfF10;

                if (T_Price > 1)
                {
                    myDatabase1.Orders.Add(orderDetail);
                    myDatabase1.SaveChanges();
                    message = "The order has been placed";
                    orderDetail.IsPlaced = true;
                }
                else
                {
                    message = "Please select at least one of the food";
                    orderDetail.IsPlaced = false;
                }
            }
            ViewBag.Message = message;
            return View(orderDetail);
        }
    }

My project is a order system so I login as a account an the data in is enter image description here

So the UserID I use is 7 but the in the order controller is return 0. How this method work and I make it keep return as 0?

For extra info, this is my user controller

        //Registration
        [HttpGet]
        public ActionResult Registration()
        {
            return View();
        }

        //Post Registration
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")]User user)
        {

            //Model Validation
            bool Status = false;
            string message = "";

            if (ModelState.IsValid)
            {
                #region Email is already exist
                var isExist = IsEmailExist(user.Email);
                if (isExist)
                {
                    ModelState.AddModelError("EmailExist", "Email already exist");
                    return View(user);
                }
                #endregion

                #region Generate Activation Code
                user.ActivationCode = Guid.NewGuid();
                #endregion

                #region Password Hashing
                user.Password = Crypto.Hash(user.Password);
                user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword);
                #endregion

                user.IsEmailVerified = false;

                #region Save Data to Database
                using (myDatabaseEntities myDatabase = new myDatabaseEntities())
                {
                    myDatabase.Users.Add(user);
                    myDatabase.SaveChanges();

                    //Send Email to User
                    SendVerificationLinkEmail(user.Email, user.ActivationCode.ToString());
                    message = "Registration successfully done. Account activation link" +
                        " has been send to your Email: " + user.Email + " Please go check and activate your account.";
                    Status = true;
                }
                #endregion

            }
            else
            {
                message = "Invalid Request";
            }

            ViewBag.Message = message;
            ViewBag.Status = Status;
            return View(user);
        }

        #region Verify Email
        [HttpGet]
        public ActionResult VerifyAccount(string id)
        {
            Boolean Status = false;
            using (myDatabaseEntities myDatabase = new myDatabaseEntities())
            {
                myDatabase.Configuration.ValidateOnSaveEnabled = false; //Avoid ConfirmPassword does not match
                var v = myDatabase.Users.Where(a => a.ActivationCode == new Guid(id)).FirstOrDefault();
                if (v != null)
                {
                    v.IsEmailVerified = true;
                    myDatabase.SaveChanges();
                    Status = true;
                }
                else
                {
                    ViewBag.Message = "Invalid Request";
                }
            }
            ViewBag.Status = Status;
            return View();
        }

        #endregion

        #region Login
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        #endregion


        #region Login POST
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(UserLogin userLogin, string ReturnUrl="")
        {
            string message = "";
            using (myDatabaseEntities myDatabase = new myDatabaseEntities())
            {
                var v = myDatabase.Users.Where(a => a.Email == userLogin.Email).FirstOrDefault();
                if (v != null)
                {
                    if (string.Compare(Crypto.Hash(userLogin.Password),v.Password) == 0)
                    {
                        int timeout = userLogin.RememberMe ? 525600 : 1; // 1 year
                        var ticket = new FormsAuthenticationTicket(userLogin.Email, userLogin.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);

                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return Redirect(ReturnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                    {
                        message = "The password is not valid";
                    }
                }
                else
                {
                    message = "The password is not valid";
                }
            }
            ViewBag.Message = message;
            return View();
        }

        #endregion

        #region Logout
        [Authorize]
        [HttpPost]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index" , "Home");
        }

        #endregion

And both of my data in table are

CREATE TABLE [dbo].[User] 
(
    [UserID]            INT              IDENTITY (1, 1) NOT NULL,
    [FirstName]         VARCHAR (50)     NOT NULL,
    [LastName]          VARCHAR (50)     NOT NULL,
    [Email]             VARCHAR (256)    NOT NULL,
    [DateOfBirth]       DATE             NULL,
    [Password]          NVARCHAR (MAX)   NOT NULL,
    [IsEmailVerified]   BIT              NOT NULL,
    [ActivationCode]    UNIQUEIDENTIFIER NOT NULL,
    [ResetPasswordCode] NVARCHAR (100)   NULL,

    PRIMARY KEY CLUSTERED ([UserID] ASC)
);

CREATE TABLE [dbo].[OrderDetails] 
(
    [OrderID]          INT  NOT NULL IDENTITY,
    [User_ID]          INT  NOT NULL,
    [OrderDate]        DATE NULL,
    [A_ChickenChop_BP] INT  NOT NULL,
    [A_ChickenChop_M]  INT  NOT NULL,
    [A_Spaghetti_AH]   INT  NOT NULL,
    [A_Spaghetti_P]    INT  NOT NULL,
    [A_Spaghetti_S]    INT  NOT NULL,
    [A_ChickenRice_CB] INT  NOT NULL,
    [A_ChickenRice_CW] INT  NOT NULL,
    [A_ChickenRice_D]  INT  NOT NULL,
    [A_WantanMee_IS]   INT  NOT NULL,
    [A_WantanMee_NS]   INT  NOT NULL,

    CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED ([OrderID] ASC),

    CONSTRAINT [FK_OrderDetails_User] 

I'm new in here so trying using this method to get the UserID and be an input to the order's User_ID. Where is the mistake I make?

Upvotes: 0

Views: 771

Answers (1)

harmath
harmath

Reputation: 303

The User.Identity.GetUserId() is working from dbo.AspNetUsers table. If you want to use your custom User table you sould choose another way to get the current user ID. You can use the Session to store and retrieve the current user ID or you can use the original Log in process and extend the dbo.AspNetUsers table with your dbo.User table.

Upvotes: 1

Related Questions