如何在注册过程中将User.Id值添加到Custom.UserId? [英] How can I add User.Id value to Custom.UserId during registration?

查看:59
本文介绍了如何在注册过程中将User.Id值添加到Custom.UserId?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将拥有一个预先填充的数据库,该数据库将具有从另一台服务器推送到该数据库的信息.列之一将是UserId,并将与ApplicationUser一对一关系.我正在使用Identity Core来确保安全性.

I will have a prepopulated Database that will have information pushed to it from another server. One of the columns will be UserId and will have a one to one relationship with ApplicationUser. I am using Identity Core for security.

如何在注册过程中收集AspNetUser.Id并将其推送到另一个表EmpProflie.UserId值?

How do I collect the AspNetUser.Id during the registration process and push it to the other table EmpProflie.UserId value?

我认为在OnPostAsync的if(result.Succeeded)期间,应该在发送电子邮件确认后的某处调用以下代码来获取AspNetUser Id的值. 显然是关于var userId的错误

I think during OnPostAsync's if(result.Succeeded) I should be able to get the value of the AspNetUser Id by calling the following code somewhere after the email confirmation is sent. Error obviously on var userId

var aspUserId = _userManager.Users.Select(e=>e.Id);
var userId = _context.EmpProfile.Add(aspUserId).Entity.UserId;

我不确定如何将该值推送给正在注册的当前用户 这样一来,它就可以派上用场了. _context.EmpProfile.UserId?????

I'm not sure how to push that value to the current user who is registering so that it's assigned off the bat. _context.EmpProfile.UserId?????

这是完整的方法:

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            var isInDb =
                _context.EmpProfile.Any(e => e.Email.ToLower() == Input.Email.ToLower());

            if (ModelState.IsValid && isInDb)
            {
                var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Password);
                
                if (result.Succeeded)
                {
                    
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    var userId = _userManager.Users.Select(e => e.Id);
                    var userId = _context.EmpProfile.Add(aspUserId).Entity.UserId; <--- ERROR

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        return LocalRedirect(returnUrl);
                    }
                }


                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

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

更新

我尝试了以下操作,但是我不确定如何仅设置UserId值.

I have tried the following but I'm not sure how to set just the UserId value.

就像用户@Fei Han在下面建议的那样,我发现如何通过昨晚的stackoverflow来获取aspnet User.Id.

Like user @Fei Han suggested below, I found how to get aspnet User.Id looking through stackoverflow last night.

var aspUserId = user.Id;
                    if (aspUserId != null)
                    {
                        var ownerId = new EmpInfo
                        {
                            UserId = aspUserId
                        };
                        _context.Update(ownerId);
                        _context.SaveChanges();
                    }

但是,当我设置该值时,这将覆盖我所有的现有数据.我 am 可以将UserId设置为正确的值.我只是现在还不知道如何只设置/更新ONE属性而不覆盖其他所有属性.

However, this is overwriting all of my existing data when I set the value. I am getting the UserId to value set properly though. I just can't figure out as of yet how to only set/update the ONE property without overwriting all the others.

推荐答案

如何在注册过程中收集AspNetUser.Id并将其推送到另一个表EmpProflie.UserId值?

How do I collect the AspNetUser.Id during the registration process and push it to the other table EmpProflie.UserId value?

如果调试代码,您会发现在创建新的IdentityUser对象时,Id属性被初始化以形成新的GUID字符串值,如下所示.

If you debug the code, you would find that the Id property is initialized to form a new GUID string value while you create a new IdentityUser object, like below.

因此,您可以修改以下代码以获取新用户的ID,然后将其存储或更新到EmpProfile表.

So you can modify the code as below to get new user's Id, then store or update to your EmpProfile table.

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");
    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
    if (ModelState.IsValid)
    {
        var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
        var result = await _userManager.CreateAsync(user, Input.Password);

        if (result.Succeeded)
        {
            //get new registered user's id
            var user_id = user.Id;

            //store or update with new reger user's id in EmpProfile table
            //...

更新:

如何仅设置/更新一个属性而不覆盖其他所有属性

how to only set/update the ONE property without overwriting all the others

要使用aspUserId更新EmpProfile UserId并保留到数据库,您可以参考以下代码段.

To update EmpProfile UserId with aspUserId and persist to the database, you can refer to the following code snippet.

var Emp = _context.EmpProfile.Where(e => e.Email.ToLower() == Input.Email.ToLower()).FirstOrDefault();

if (ModelState.IsValid && Emp != null)
{
    var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
    var result = await _userManager.CreateAsync(user, Input.Password);

    if (result.Succeeded)
    {
        //get new registered user's id
        var aspUserId = user.Id;

        //store or update with new reger user's id in EmpProfile table
        //...

        if (aspUserId != null)
        {
            Emp.UserId = aspUserId;

            //By default, queries that return entity types are tracking
            //can make changes to those entity instances and have those changes persisted by SaveChanges()

            _context.SaveChanges();
        }

这篇关于如何在注册过程中将User.Id值添加到Custom.UserId?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆