Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# User.Identity.GetUserId()在ASP.NET MVC5中的工作方式_C#_Asp.net Mvc - Fatal编程技术网

C# User.Identity.GetUserId()在ASP.NET MVC5中的工作方式

C# User.Identity.GetUserId()在ASP.NET MVC5中的工作方式,c#,asp.net-mvc,C#,Asp.net Mvc,如标题所述,我已经使用此方法识别项目中的用户id。同时,我也看到了这篇文章,但我的输出仍然与用户id不匹配。基本上,用户id的输出是这样的 我的MVC5控制器代码是 public class OrderController : Controller { [Authorize] [HttpGet] public ActionResult PlaceOrder() { return View();

如标题所述,我已经使用此方法识别项目中的用户id。同时,我也看到了这篇文章,但我的输出仍然与用户id不匹配。基本上,用户id的输出是这样的

我的MVC5控制器代码是

    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);
        }
    }
我的项目是一个订单系统,所以我作为一个帐户登录,其中的数据是

所以我使用的UserID是7,但是order控制器中的返回值是0。这个方法是如何工作的,我让它保持返回为0

关于额外信息,这是我的用户控制器

        //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
表中的两个数据都是

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] 

我是新来的,所以尝试使用此方法获取用户ID并作为订单用户ID的输入。我犯的错误在哪里?

User.Identity.GetUserId正在dbo.AspNetUsers表中工作。如果要使用自定义用户表,则应选择另一种获取当前用户ID的方法。您可以使用会话存储和检索当前用户ID,也可以使用原始登录过程并使用dbo.User表扩展dbo.AspNetUsers表