简体   繁体   English

如何在ASP.Net MVC实体框架的帐户控制器中传递来自登录方法的ID?

[英]How can I pass the Id from Login method in Account Controller in ASP.Net MVC Entity Framework?

I've been working on an ASP.Net MVC application based within a .NET Entity Framework. 我一直在研究基于.NET实体框架ASP.Net MVC应用程序 Within it I set the authentication to individual User Account s to allow a Login/Register process to occur on the application. 在其中,我将身份验证设置为单个用户帐户,以允许在应用程序上进行登录/注册过程。

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数据

ASPNetUsers 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. 如您所见,Id是使用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"); 重要的是要注意,在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,以便用户可以创建具有用户ID的配置文件,该用户ID可用于将其与特定配置文件相关联。

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

AddNAA_Profile View after user clicks Register 用户单击注册后的AddNAA_Profile视图

在此处输入图片说明

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. 您会看到在登录的情况下,我不确定如何像在Register函数中那样携带id。 As in the register function the id is generated inside the method, but it's not the same case here. 就像在寄存器函数中一样,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; 一位讲师告诉我,在Case SigninStatus.Success上使用此方法拉取了user.id line. 线。

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. GetNAA_Profile2方法可以与我在RouteConfig文件中定义的UserId一起正常使用。 I just need to work on a means of sending the id to the method from the login. 我只需要研究一种从登录名发送ID到方法的方法。

So the main question is how do I take the id from the Login method and pass it into the GetNAA_Profile2 method? 因此,主要问题是如何从登录方法中获取ID并将其传递给GetNAA_Profile2方法?

Update [07/03/2018] 更新[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。

Inside your switch function use the following code for success 在您的switch函数内部,使用以下代码成功

     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);
    }

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将输入/文本框字段传递给控制器​​? ASP.NET MVC和实体框架 - How can I pass an input/Textbox Field to Controller? ASP.NET MVC and Entity Framework 如何将 ID 传递给 ASP.NET MVC 中的控制器? - How do I pass an ID to the controller in ASP.NET MVC? ASP.NET MVC 将参数从 controller 传递到没有实体框架的存储过程 - ASP.NET MVC pass parameter to stored procedure from controller without Entity Framework 如何使用使用 hash 加密、C#、ASP.NET MVC、实体框架的存储过程验证帐户 - How can I validate an account with a stored procedure that uses hash encryption, C#, ASP.NET MVC, Entity Framework 来自区域中控制器的ASP.NET MVC [Authorize]在根文件夹中找不到Account / Login ActionResult - ASP.NET MVC [Authorize] from controller in area can't find Account/Login ActionResult in root folder 如何将对象从我的视图传递到 ASP.NET MVC 中的控制器? - How can I pass an object from my view to my controller in ASP.NET MVC? 如何将隐藏字段值从视图传递到控制器 ASP.NET MVC 5? - How can I pass hidden field value from view to controller ASP.NET MVC 5? 如何使用POST将复杂对象从视图传递到控制器-ASP.NET MVC - How can i pass complex object from view to controller with POST - ASP.NET MVC 我如何使用 datapost 将参数从 jqgrid 传递到 controller(使用 MVC4 和 asp.net) - how can i pass parameter from jqgrid to controller with datapost (using MVC4 and asp.net ) 实体框架和ASP.NET MVC:无法从另一个控制器进入我控制器上的[HttpPost] - Entity Framework & ASP.NET MVC: can't get to the [HttpPost] on my controller from another one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM