C# Can';t向Web Api添加用户角色

C# Can';t向Web Api添加用户角色,c#,asp.net,asp.net-mvc,asp.net-web-api2,C#,Asp.net,Asp.net Mvc,Asp.net Web Api2,我正在从事一个项目,该项目要求用户具有某些角色来限制对API函数的访问。 当我尝试向给定角色添加用户时,我会遇到一个我真的不理解的异常,因为所提到的声明是在identity中定义的 异常和堆栈 "ClassName": "System.ArgumentException", "Message": "The property 'Logins' on type 'ApplicationUser' is not a navigation property. The Reference and Coll

我正在从事一个项目,该项目要求用户具有某些角色来限制对API函数的访问。 当我尝试向给定角色添加用户时,我会遇到一个我真的不理解的异常,因为所提到的声明是在identity中定义的

异常和堆栈

"ClassName": "System.ArgumentException",
"Message": "The property 'Logins' on type 'ApplicationUser' is not a navigation property. The Reference and Collection methods can only be used with navigation properties. Use the Property or ComplexProperty method.",
"Data": null,
"InnerException": null,
"HelpURL": null,
"StackTraceString": " at System.Data.Entity.Internal.InternalEntityEntry.ValidateAndGetNavigationMetadata(String navigationProperty, Type requestedType, Boolean requireCollection) at System.Data.Entity.Internal.InternalEntityEntry.Collection(String navigationProperty, Type requestedType) at System.Data.Entity.Infrastructure.DbEntityEntry`1.Collection[TElement](String navigationProperty) at System.Data.Entity.Infrastructure.DbEntityEntry`1.Collection[TElement](Expression`1 navigationProperty) at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.AreLoginsLoaded(TUser user) at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.<EnsureLoginsLoaded>d__69.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.<GetUserAggregateAsync>d__6c.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.Identity.TaskExtensions.CultureAwaiter`1.GetResult() at Microsoft.AspNet.Identity.UserManager`2.<AddToRoleAsync>d__83.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at VmeRust_Server.Controllers.AccountController.<Register>d__16.MoveNext() in C:\Users\kevom\source\repos\Rust VIP Manager\VmeRust_Server\Controllers\AccountController.cs:line 205",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": "8 ValidateAndGetNavigationMetadata EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=censored System.Data.Entity.Internal.InternalEntityEntry System.Data.Entity.Internal.NavigationEntryMetadata ValidateAndGetNavigationMetadata(System.String, System.Type, Boolean)",
"HResult": -2147024809,
"Source": "EntityFramework",
"WatsonBuckets": null,
"ParamName": null

The property 'Logins' on type 'ApplicationUser' is not a navigation property. The Reference and Collection methods can only be used with navigation properties. Use the Property or ComplexProperty method."
“ClassName”:“System.ArgumentException”,
“消息”:“类型'ApplicationUser'上的属性'Logins'不是导航属性。引用和收集方法只能与导航属性一起使用。请使用属性或ComplexProperty方法。”,
“数据”:空,
“InnerException”:null,
“帮助URL”:空,
“StackTraceString”:“在System.Data.Entity.Internal.InternalEntityEntry.ValidateAndGetNavigationMetadata(String navigationProperty,Type requestedType,Boolean Requiremollection)在System.Data.Entity.Internal.InternalEntityEntry.Collection(String navigationProperty,Type requestedType)位于System.Data.Entity.Infrastructure.DbEntityEntry`1.Collection[TElement](字符串导航属性)位于System.Data.Entity.Infrastructure.DbEntityEntry`1.Collection[TElement](表达式`1导航属性)位于Microsoft.AspNet.Identity.EntityFramework.UserStore`6.AreLoginsLoaded(TUser用户)在Microsoft.AspNet.Identity.EntityFramework.UserStore`6.d__69.MoveNext()---从引发异常的上一个位置开始的堆栈结束跟踪---在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务任务)在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务任务任务)中在Microsoft.AspNet.Identity.EntityFramework.UserStore`6.d_u6c.MoveNext()---从引发异常的上一个位置开始的堆栈结束跟踪---在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务任务)在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务任务任务任务)位于Microsoft.AspNet.Identity.TaskExtensions.CultureAwater`1.GetResult(),位于Microsoft.AspNet.Identity.UserManager`2.d__83.MoveNext()---从引发异常的前一个位置开始的堆栈结束跟踪---位于System.Runtime.CompilerServices.TaskAwaiter.ThrowForOnSuccess(任务任务)在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务任务)在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()在VmeRust\U服务器上。控制器。AccountController.d\u 16.MoveNext()在C:\Users\kevom\source\repos\Rust VIP Manager\VmeRust\U Server\Controllers\AccountController.cs:第205行“,
“RemoteStackTraceString”:空,
“RemoteStackIndex”:0,
“ExceptionMethod”:“8 ValidateAndGetNavigationMetadata EntityFramework,版本=6.0.0,区域性=中性,PublicKeyToken=受审查的System.Data.Entity.Internal.InternalEntityEntry System.Data.Entity.Internal.NavigationEntryMetadata ValidateAndGetNavigationMetadata(System.String,System.Type,布尔)”,
“HResult”:-2147024809,
“来源”:“EntityFramework”,
“WatsonBuckets”:空,
“ParamName”:空
类型“ApplicationUser”上的属性“Logins”不是导航属性。引用和收集方法只能与导航属性一起使用。使用Property或ComplexProperty方法。“
如果一个用户试图创建一个已经存在的用户,我也会遇到同样的错误

注册码

    // POST api/Account/Register
    [System.Web.Http.AllowAnonymous]
    //[System.Web.Http.Authorize(Roles = "SubscriptionManager")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser
        {
            UserName = model.Email,
            Email = model.Email,
            AccountClosed = false,
            LastLoginDateUtc = DateTime.Now,
            LastLoginIp = Request.GetOwinContext().Request.RemoteIpAddress,
            //CreatedBy = new Guid(User.Identity.GetUserId()),
            AccessFailedCount = 0,
            DateCreated = DateTime.Now,

        };

        // Register the user
        try
        {
            var result = await UserManager.CreateAsync(user, model.Password);


            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }
        }
        catch (Exception e)
        {
            return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, $"User was not created: {e.Message}"));
        }

        // Add user to Role
        try
        {
        #if DEBUG

            await UserManager.AddToRoleAsync(user.Id, VmeRoles.Developer);
        #else
            await UserManager.AddToRoleAsync(user.Id, VmeRoles.VmeUser);
        #endif
        }
        catch (Exception e)
        {
            return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, e.Message));
        }
        return Ok();
    }
//发布api/帐户/注册
[System.Web.Http.AllowAnonymous]
//[System.Web.Http.Authorize(Roles=“SubscriptionManager”)]
公共异步任务寄存器(RegisterBindingModel模型)
{
如果(!ModelState.IsValid)
{
返回请求(ModelState);
}
var user=新应用程序用户
{
用户名=model.Email,
Email=model.Email,
AccountClosed=false,
LastLoginDeutc=日期时间。现在,
LastLoginIp=Request.GetOwinContext().Request.RemoteIpAddress,
//CreatedBy=新Guid(User.Identity.GetUserId()),
AccessFailedCount=0,
DateCreated=DateTime。现在,
};
//注册用户
尝试
{
var result=await UserManager.CreateAsync(用户、模型、密码);
如果(!result.successed)
{
返回GetErrorResult(结果);
}
}
捕获(例外e)
{
返回响应消息(Request.CreateResponse(HttpStatusCode.InternalServerError,$“未创建用户:{e.Message}”);
}
//将用户添加到角色
尝试
{
#如果调试
等待UserManager.AddToRoleAsync(user.Id,VmeRoles.Developer);
#否则
等待UserManager.AddToRoleAsync(user.Id,VmeRoles.VmeUser);
#恩迪夫
}
捕获(例外e)
{
返回响应消息(Request.CreateResponse(HttpStatusCode.InternalServerError,e.Message));
}
返回Ok();
}
这是上下文代码

    public class ApplicationUser : IdentityUser
{
    /// <summary>
    /// Gets or sets the subscription
    /// </summary>
    public Subscription UserSubscription { get; set; } 
    /// <summary>
    /// The date account was created
    /// </summary>
    public System.DateTime? DateCreated { get; set; }
    /// <summary>
    /// Who Created the Account
    /// </summary>
    public System.Guid CreatedBy { get; set; }
    /// <summary>
    /// Last Login activity of the account (date)
    /// </summary>
    public System.DateTime? LastLoginDateUtc { get; set; }
    /// <summary>
    /// Last login acitivity of the account (IP)
    /// </summary>
    public string LastLoginIp { get; set; }
    /// <summary>
    /// Indicates if the account is closed
    /// </summary>
    public bool AccountClosed { get; set; }
    /// <summary>
    /// Indicates the date the account was closed
    /// </summary>
    public System.DateTime? AccountCLosedTime { get; set; }
    /// <summary>
    /// Indicates if the account is pending a password reset 
    /// </summary>
    public bool? PasswordReset { get; set; }
    /// <summary>
    /// Indicates if the account is pending a password reset 
    /// </summary>
    public string PasswordResetToken { get; set; }
    /// <summary>
    /// Indicates if the account is pending a password reset 
    /// </summary>
    public DateTime? PasswordResetTokenExpriry { get; set; }
    /// <summary>
    /// The last Login session Id
    /// </summary>
    public string LastSessionId { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
        // Add custom user claims here
        return userIdentity;
    }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

/// <summary>
/// A data set that contains basic information about a subcription
/// </summary>
public class Subscription 
{
    // Some code ...
    public Guid AddedByUser { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("VmeRustDev", throwIfV1Schema: false)
    {
    }
    /// <summary>Logins
    /// Gets or sets the SubScription Data set
    /// </summary>
    public DbSet<Subscription> Subscription { get; set; }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ApplicationUser>().ToTable("Users").HasKey(i => i.Id);
        modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles").HasKey(i => i.RoleId);
        modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims").HasKey(i => i.Id);
        modelBuilder.Entity<IdentityRole>().ToTable("Roles").HasKey(i => i.Id);
        modelBuilder.Ignore<IdentityUserLogin>();
    }
}
公共类应用程序用户:IdentityUser
{
/// 
///获取或设置订阅
/// 
公共订阅用户订阅{get;set;}
/// 
///创建帐户的日期
/// 
public System.DateTime?DateCreated{get;set;}
/// 
///谁创建了这个帐户
/// 
public System.Guid由{get;set;}创建
/// 
///帐户的上次登录活动(日期)
/// 
public System.DateTime?LastLoginDeutc{get;set;}
/// 
///帐户的上次登录活动(IP)
/// 
公共字符串LastLoginIp{get;set;}
/// 
///指示帐户是否已关闭
/// 
公共bool AccountClosed{get;set;}
/// 
///指示帐户关闭的日期
/// 
public System.DateTime?AccountCLosedTime{get;set;}
/// 
///指示帐户是否正在等待密码重置
/// 
公共bool?密码重置{get;set;}
/// 
///指示帐户是否正在等待密码重置
/// 
公共字符串密码重置令牌{g
public ICollection<Role> Roles { get; set; }
public class Role : IdentityRole
{
    public ICollection<ApplicationUser> Users { get; set; }
}
    public class ApplicationRoleManager : RoleManager<Role>
    {
       public ApplicationRoleManager(IRoleStore<Role, string> store) : base(store)
       {
       }
       public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
       {
         var roleStore = new RoleStore<Role>(context.Get<SecurityDbContext>());
         return new ApplicationRoleManager(roleStore);
       }
    }