.net核心身份用户ID与数据库不同

时间:2017-07-30 03:53:01

标签: .net asp.net-mvc entity-framework-core identity core

我正在尝试使用.NET Core中的身份获取当前用户的id。管理创建新用户并使用它登录,但只要使用相同的用户身份登录,就会返回不同的guid。

我有一个产品实体,它将userId存储为外键。每当我尝试添加新产品时,它都会引发错误,因为userId不在用户表中。

但我注册了一个新用户并立即添加新产品。列出产品。 Hovewer,注销并再次使用相同的用户登录,产品未列出。当我调试时,看到_userManager.GetUserId(User)返回不同的值。

为什么会这样?

我该如何解决这个问题?

更新 我的用户创建代码

var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    await _signInManager.SignInAsync(user, isPersistent: false);

    return RedirectToAction(nameof(HomeController.Index), "Home");
}

我的用户登录代码

var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);

if (result.Succeeded)
{
    return RedirectToLocal(returnUrl);
}

这是我的ApplicationUser Model Class

public class ApplicationUser : IdentityUser
{

    [Key]
    [Column("TABLEID")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override string Id { get; set; }

    [Required]
    [Column("AD")]
    public string Name { get; set; }

    [Required]
    [Column("SOYAD")]
    public string Surname { get; set; }

    [Required]
    [Column("AKTIF")]
    public bool IsActive { get; set; }

    [Required]
    [Column("SIL")]
    public bool IsDeleted { get; set; }

    [Required]
    [Column("KAYITTARIHI")]
    public DateTime RecordDate { get; set; }

    public List<Vehicle> Vehicles { get; set; }
    public List<VehicleImage> VehicleImages { get; set; }
    public List<TransportAdvertise> TansportAdvertises { get; set; }
    public List<TransportRequest> TransportRequests { get; set; }

}

这是我的DbContext

public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public DbSet<Vehicle> Vehicles { get; set; }
    public DbSet<VehicleImage> VehicleImages { get; set; }
    public DbSet<TransportAdvertise> TransportAdvertises { get; set; }
    public DbSet<TransportRequest> TransportRequests { get; set; }
    public DbSet<TransportRoute> TransportRoutes { get; set; }
    public DbSet<City> Cities { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {

        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        // Identity built-in models.
        builder.Entity<IdentityUser>().ToTable("TBLKULLANICI");
        builder.Entity<IdentityRole>().ToTable("TBLROL");
        builder.Entity<IdentityUserRole<string>>().ToTable("TBLKULLANICIROL");
        builder.Entity<IdentityRoleClaim<string>>().ToTable("TBLROLECLAIM");
        builder.Entity<IdentityUserClaim<string>>().ToTable("TBLUSERCLAIM");
        builder.Entity<IdentityUserLogin<string>>().ToTable("TBLUSERLOGIN");
        builder.Entity<IdentityUserToken<string>>().ToTable("TBLUSERTOKEN");

        // Custom models.
        builder.Entity<Vehicle>().ToTable("TBLARAC");
        builder.Entity<VehicleImage>().ToTable("TBLARACRESIM");
        builder.Entity<TransportAdvertise>().ToTable("TBLNAKLIYEILAN");
        builder.Entity<TransportRequest>().ToTable("TBLNAKLIYEISTEK");
        builder.Entity<TransportRoute>().ToTable("TBLROTA");
        builder.Entity<City>().ToTable("TBLSEHIR");

        // FK mappings..
        builder.Entity<Vehicle>()
                .HasOne(v => v.User)
                .WithMany(u => u.Vehicles)
                .HasForeignKey(v => v.UserId)
                .HasConstraintName("FK_VEHICLE_USER");

        // Vehicle image model fks.
        builder.Entity<VehicleImage>()
                .HasOne(vi => vi.Vehicle)
                .WithMany(v => v.Images)
                .HasForeignKey(vi => vi.VehicleId)
                .HasConstraintName("FK_VEHICLE_IMAGE_VEHICLE");

        builder.Entity<VehicleImage>()
                .HasOne(vi => vi.User)
                .WithMany(u => u.VehicleImages)
                .HasForeignKey(vi => vi.UserId)
                .HasConstraintName("FK_VEHICLE_IMAGE_USER");

        // TransportAdvertise model fks.
        builder.Entity<TransportAdvertise>()
                .HasOne(ta => ta.User)
                .WithMany(u => u.TansportAdvertises)
                .HasForeignKey(ta => ta.UserId)
                .HasConstraintName("FK_TRANSPORT_ADS_USER");

        builder.Entity<TransportAdvertise>()
                .HasOne(ta => ta.Vehicle)
                .WithMany(v => v.TransportAdvertises)
                .HasForeignKey(ta => ta.VehicleId)
                .HasConstraintName("FK_TRANSPORT_ADS_VEHICLE");

        // TransportRequest model fks.
        builder.Entity<TransportRequest>()
                .HasOne(tr => tr.User)
                .WithMany(u => u.TransportRequests)
                .HasForeignKey(tr => tr.UserId)
                .HasConstraintName("FK_TRANSPORT_RQST_USER");

        builder.Entity<TransportRequest>()
                .HasOne(tr => tr.TransportAdvertise)
                .WithMany(ta => ta.TransportRequests)
                .HasForeignKey(tr => tr.TransportAdvertiseId)
                .HasConstraintName("FK_TRANSPORT_RQST_ADS");

        // TransportRoute model fks.
        builder.Entity<TransportRoute>()
                .HasOne(tr => tr.City)
                .WithMany(c => c.TransportRoutes)
                .HasForeignKey(tr => tr.CityId)
                .HasConstraintName("FK_TRANSPORT_ROUTE_CITY");

        builder.Entity<TransportRoute>()
                .HasOne(tr => tr.TransportAdvertise)
                .WithMany(ta => ta.TransportRoutes)
                .HasForeignKey(tr => tr.TransportAdvertiseId)
                .HasConstraintName("FK_TRANSPORT_ROUTE_ADS");

    }

车辆创建代码

[HttpPost]
    public IActionResult AddNewVehicle(VehicleViewModel model)
    {
        var id = _userManager.GetUserId(User);

        // model property check needs to be done before.
        // vehicle table does not accept nulls.

        var vehicle = new Vehicle()
        {
            Model = model.Model,
            Capacity = model.Capacity,
            Description = model.Description,
            Year = model.Year,
            Active = true,
            Delete = false,
            RecordDate = DateTime.Now,
            UserId = id
        };

        _vehicleService.AddNew(vehicle);

        return RedirectToAction("Index");
    }

1 个答案:

答案 0 :(得分:0)

进行简单的实验...创建新用户并记下其ID ...立即添加产品,并在保存操作后再次检查用户ID是否已更改。在保存操作时,用户详细信息可能会发生变化/更改。您还可以粘贴代码示例以创建用户,创建产品并在此处检索用户。问题很可能是你在拯救车辆的地方。此时,用户详细信息要么发生变异,要么车辆与其他用户一起存储。车辆与用户具有1对1的关系。所以在创建车辆时要小心不要做vehicle.user = new User;确保您正在执行以下操作。 1-从Db获取用户:

  

var user = await UserManager.FindByIdAsync(&#34;当前登录的ID   用户&#34);

2-将vehicle.user设置为上面检索到的用户:

  

vehicle.user = user。

您可以共享代码,以便为人们提供帮助。您还可以阻止在数据库中自动生成用户ID,并在Id字段中添加[Required]属性。你可以做到

  

user.Id = Guid.Guid.NewGuid()

。这可以帮助防止在创建车辆时自动将新用户添加到数据库的问题