我无权访问IdentityUser的默认属性中的“添加”属性

时间:2019-12-25 16:49:54

标签: c# entity-framework asp.net-core

我想使用添加到IdentityUser默认属性中但属性为icant的属性。

Strtup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentity<IdentityUser, IdentityRole>(options =>
        {
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 6;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequireLowercase = true;
            options.User.RequireUniqueEmail = true;
            // Lockout settings.
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Lockout.MaxFailedAccessAttempts = 5;
            options.Lockout.AllowedForNewUsers = true;

        }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
       }

ApplicationDbContext.cs

public partial class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder builder) 
    {
        base.OnModelCreating(builder);
    }

}

ApplicationUser.cs

    public class ApplicationUser : IdentityUser
{
    public int Coin { get; set; }
}

在这一课上,我无法更改硬币的价值

硬币是IdentityUser的默认属性中的添加属性 AccountController.cs

public class AccountController : Controller
{
    private readonly UserManager<IdentityUser> _userManager;

    private readonly SignInManager<IdentityUser> _signManager;
    private readonly ApplicationDbContext _db;

    private readonly AppSettings _appSettings;


    public AccountController(UserManager<IdentityUser> userManager,
        SignInManager<IdentityUser> signInManager
        ,
        IOptions<AppSettings> appSettings,
        ApplicationDbContext db
        //IEmailSender emailsender
        )
    {
        _userManager = userManager;
        _signManager = signInManager;
        _appSettings = appSettings.Value;
        _db = db;
    }
    [HttpPost("[action]")]
    public async Task<IActionResult> Register([FromBody] RegisterViewModel formdata)
    {
        var errorList = new ErrorLoginReg();
        var user = new IdentityUser
        {
            Email = formdata.Email,
            UserName = formdata.UserName,
            SecurityStamp = Guid.NewGuid().ToString()
        };

        var result = await _userManager.CreateAsync(user, formdata.Password);
        Dictionary<string, string> styleError = new Dictionary<string, string>();

        if (result.Succeeded)
        {
            await _userManager.AddToRoleAsync(user, "Customer");
            var dbUser = _db.Users.Where(a => a.Id == user.Id).First();
            dbUser.Coin =1500; //Error
             _db.Users.Update(dbUser);

            await _db.SaveChangesAsync();

            return Ok(new { success=true, username = user.UserName, email = user.Email, status = 1, message = "Registration Successful" });

        }
        else
        {
            errorList.success = false;

            List<errormodel> deserror = new List<errormodel>();
            foreach (var error in result.Errors)
            {
                styleError.Add(error.Code, error.Description);
                ModelState.AddModelError("", error.Description);
                var ermo = new errormodel();
                ermo.code = error.Code;
                ermo.message = error.Description;
                deserror.Add(ermo);
            }
            errorList.error = deserror;

        }

        return Json(errorList);

    }

我无权访问AccountController中的硬币!

1 个答案:

答案 0 :(得分:1)

  

我无权访问AccountController中的硬币!

它不存在,因为您实际上并未指示Identity使用您的ApplicationUser类而不是IdentityServer类。

需要发生三件事

  • 数据库上下文需要了解您的ApplicationUser类。因此,您将上下文更改为:
public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser>
  • 对addIdentity的调用也需要使用ApplicationUser类
services.AddIdentity<ApplicationUser, IdentityRole>(options => { .. });
  • 应该通过在Coin列中扩展数据库,方法是在之前的更改之后添加迁移,然后更新数据库。
> add-migration add_coin_to_user -c ApplicationDbContext

> update-database -c ApplicationDbContext

编辑: 取决于IdentityUser的所有服务还应使用与启动时注册服务时相同的TKey。

  • 这意味着改变

private readonly UserManager<IdentityUser> _userManager;

private readonly UserManager<ApplicationUser> _userManager;

对于采用IdentityUser的每个服务,依此类推。