如何从ASP.Net MVC实体框架中的帐户控制器中的Login方法传递Id?

时间:2022-12-02 15:04:13

I've been working on an ASP.Net MVC application based within a .NET Entity Framework. Within it I set the authentication to individual User Accounts to allow a Login/Register process to occur on the application.

我一直在研究基于.NET实体框架的ASP.Net MVC应用程序。在其中,我将身份验证设置为单个用户帐户,以允许在应用程序上进行登录/注册过程。

As you know when a user registers on the application they are added into the ASPNetUsers table with a unique id generated which is used to identify the user.

如您所知,当用户在应用程序上注册时,会将它们添加到ASPNetUsers表中,并生成用于标识用户的唯一ID。

ASPNetUsers Columns and Datatypes

ASPNetUsers列和数据类型

CREATE TABLE [dbo].[AspNetUsers] (
[Id]                   NVARCHAR (128) NOT NULL,
[Email]                NVARCHAR (256) NULL,
[EmailConfirmed]       BIT            NOT NULL,
[PasswordHash]         NVARCHAR (MAX) NULL,
[SecurityStamp]        NVARCHAR (MAX) NULL,
[PhoneNumber]          NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT            NOT NULL,
[TwoFactorEnabled]     BIT            NOT NULL,
[LockoutEndDateUtc]    DATETIME       NULL,
[LockoutEnabled]       BIT            NOT NULL,
[AccessFailedCount]    INT            NOT NULL,
[UserName]             NVARCHAR (256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);

ASPNetUsers id data

ASPNetUsers id数据

如何从ASP.Net MVC实体框架中的帐户控制器中的Login方法传递Id?

The methods for the login and register function are all located within the Account Controller. In the Account Controller I did an initial process which took the id generated for the user when they register.

登录和注册功能的方法都位于帐户控制器中。在帐户控制器中,我做了一个初始过程,该过程在用户注册时获取了为用户生成的id。

Register function in AccountController

在AccountController中注册函数

As you can see the Id is passed from the register function using a RedirectToAction. It's important to note the RedirectToAction is used after the id is defined within the code by the UserManager.AddToRole(user.Id, "User");

如您所见,使用RedirectToAction从寄存器功能传递Id。重要的是要注意在UserManager.AddToRole(user.Id,“User”)在代码中定义id之后使用RedirectToAction;

The RedirectToAction method passes the id forward to my AddNAA_Profile method defined in a separate controller called NAAProfileController

RedirectToAction方法将id转发到我在另一个名为NAAProfileController的控制器中定义的AddNAA_Profile方法。

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {

        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                UserManager.AddToRole(user.Id, "User");
                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("AddNAA_Profile",  new { UserId = user.Id, Controller = "NAAAdmin" });
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

AddNAA_Profile Method in NAAAdminController

NAAAdminController中的AddNAA_Profile方法

In the AddNAA_profile GET method the UserId is set up to display the id within the view so the user can create a profile with an userid which can be used to associate them to the specific profile.

在AddNAA_profile GET方法中,UserId设置为在视图中显示id,以便用户可以使用userid创建配置文件,该用户ID可用于将它们与特定配置文件相关联。

  [HttpGet]
    public ActionResult AddNAA_Profile(string UserId)
    {
        ViewBag.User_ID = UserId;
        return View();
    }

AddNAA_Profile View after user clicks Register

用户单击“注册”后添加NAA_Profile视图

如何从ASP.Net MVC实体框架中的帐户控制器中的Login方法传递Id?

So now you know how I did the register function I wanted to get your professional opinion on how I can proceed to do some similar type of conditioning with user Logins.

所以现在你知道我是如何做注册函数的,我希望得到你对如何使用用户登录进行类似类型的调节的专业意见。

You see in the case of a Login I'm not sure how to carry the id as I did with the Register function. As in the register function the id is generated inside the method, but it's not the same case here.

你看到在登录的情况下,我不知道如何携带id,就像我使用Register函数一样。在register函数中,id是在方法内生成的,但这里的情况并不相同。

Login Method in Account Controller

帐户控制器中的登录方法

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:

                return RedirectToLocal(returnUrl);



            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.If you do not have an account please register one");
                return View(model);
        }
    }

I was told by lecturer that the user.id is pulled in this method on the Case SigninStatus.Success; line.

讲师告诉我,user.id在Case SigninStatus.Success中被拉入此方法;线。

However when I tried to implement the same type of RedirectToAction process I kept getting an error where it said "the name user doesn't exist in this context"

但是,当我尝试实现相同类型的RedirectToAction进程时,我不断收到错误,其中说“在此上下文中不存在名称用户”

   var result = await SignInManager.PasswordSignInAsync(model.Email, 
   model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToAction("GetNAA_Profile2", new { UserId = user.Id, Controller = "NAAAdmin" }); 

            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.If you do not have an account please register one");
                return View(model);
        }
    }

You see what I'm trying to do is pass the id from the login into my GetNAA_Profile2 method which checks for the respective profile linking with the id passed through

你看到我想要做的是将登录中的id传递给我的GetNAA_Profile2方法,该方法检查链接的相应配置文件与通过的id

GetNAA_Profile2 method in Profile Controller

Profile Controller中的GetNAA_Profile2方法

   public ActionResult GetNAA_Profile2(string UserId)
    {
        return View(_NAAService.GetNAA_Profile2(UserId));
    }

The GetNAA_Profile2 method works properly with the UserId I defined in my RouteConfig file. I just need to work on a means of sending the id to the method from the login.

GetNAA_Profile2方法与我在RouteConfig文件中定义的UserId一起正常工作。我只需要在登录时将id发送到方法。

So the main question is how do I take the id from the Login method and pass it into the GetNAA_Profile2 method?

所以主要的问题是我如何从Login方法中获取id并将其传递给GetNAA_Profile2方法?

Update [07/03/2018]

I've tried implementing the lines

我试过实现这些线

ApplicationUser CurrentUser = UserManager.FindByEmail(model.Email);

and

var GUID = System.Web.HttpContext.Current.User.Identity.GetUserId();

But despite this, the values returned from these lines always remain NULL.

但尽管如此,从这些行返回的值始终保持为NULL。

2 个解决方案

#1


0  

Inside your switch function use the following code for success

在您的交换机功能内部使用以下代码获取成功

     switch (result)
    {
        case SignInStatus.Success:

      ApplicationUser CurrentUser = UserManager.FindByEmail(model.Email);
//Use this "CurrentUser" Id for your function.

        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.If you do not have an account please register one");
            return View(model);
    }

#2


0  

did you tried debugging put a breakpoint on success and see if the controls reach there, because i use the same code to get current users id while logging into the application.

你是否尝试过调试成功断点,看看控件是否到达那里,因为我在登录应用程序时使用相同的代码来获取当前用户ID。

Another approach to find current users ID would be

找到当前用户ID的另一种方法是

var GUID = System.Web.HttpContext.Current.User.Identity.GetUserId();

var GUID = System.Web.HttpContext.Current.User.Identity.GetUserId();

This GUID Will be the aspnetusers ID that was generated while user registered.

此GUID将是用户注册时生成的aspnetusers ID。

#1


0  

Inside your switch function use the following code for success

在您的交换机功能内部使用以下代码获取成功

     switch (result)
    {
        case SignInStatus.Success:

      ApplicationUser CurrentUser = UserManager.FindByEmail(model.Email);
//Use this "CurrentUser" Id for your function.

        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.If you do not have an account please register one");
            return View(model);
    }

#2


0  

did you tried debugging put a breakpoint on success and see if the controls reach there, because i use the same code to get current users id while logging into the application.

你是否尝试过调试成功断点,看看控件是否到达那里,因为我在登录应用程序时使用相同的代码来获取当前用户ID。

Another approach to find current users ID would be

找到当前用户ID的另一种方法是

var GUID = System.Web.HttpContext.Current.User.Identity.GetUserId();

var GUID = System.Web.HttpContext.Current.User.Identity.GetUserId();

This GUID Will be the aspnetusers ID that was generated while user registered.

此GUID将是用户注册时生成的aspnetusers ID。