Прежде всего, таких вопросов много, но это не дублируется, потому что мой код действительно отличается от других.
Я хочу реализовать членство, используя Asp.net MVC Identity. Но я не могу справиться с этой ошибкой. Давайте посмотрим на коды:
IdentityStratup.cs
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.AspNet.Identity;
using Login.Models;
[assembly: OwinStartup(typeof(Login.App_Start.Startup))]
namespace Login.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
app.CreatePerOwinContext(MyDbContext.Create);
}
}
}
В папке Identity → ApplicationRole.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Login.Identity
{
public class ApplicationRole : IdentityRole
{
public string Description { get; set; }
public ApplicationRole ()
{
}
public ApplicationRole (string roleName, string description) : base(roleName)
{
this.Description = description;
}
}
}
В папке Identity → ApplicationUser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Login.Identity
{
public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public string Surname { get; set; }
}
}
Login.cs в папке Models
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Login.Models
{
public class Login
{
[Required]
[StringLength(50)]
[RegularExpression(@"^(?=[a-zA-Z])[-\w.]{0,23}([a-zA-Z\d]|(?<![-.])_)$")]
public string UserName { get; set; }
[Required]
[RegularExpression(@"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DisplayName("Remember Me")]
public bool RememberMe { get; set; }
}
}
Register.cs в папке Models
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Login.Models
{
public class Register
{
[Key]
[Required]
public int ID { get; set; }
[Required]
[StringLength(50)]
[RegularExpression(@"^(([A-za-z]+[\s]{1}[A-za-z]+)|([A-Za-z]+))$")]
public string Name { get; set; }
[Required]
[StringLength(50)]
[RegularExpression(@"^(([A-za-z]+[\s]{1}[A-za-z]+)|([A-Za-z]+))$")]
public string Surname { get; set; }
[Required]
[StringLength(50)]
[RegularExpression(@"^(?=[a-zA-Z])[-\w.]{0,23}([a-zA-Z\d]|(?<![-.])_)$")]
public string Username { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[RegularExpression(@"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[RegularExpression(@"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$")]
[Compare("Password")]
public string PasswordConfirmation { get; set; }
}
}
Global.asasx
using Login.Identity;
using Login.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Login
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
MyDbContext db = new MyDbContext();
RoleStore<ApplicationRole> roleStore = new RoleStore<ApplicationRole>(db);
RoleManager<ApplicationRole> roleManager = new RoleManager<ApplicationRole>(roleStore);
if (!roleManager.RoleExists("Admin"))
{
ApplicationRole adminRole = new ApplicationRole("Admin", "System Admnistrator");
roleManager.Create(adminRole);
}
if (!roleManager.RoleExists("User"))
{
ApplicationRole userRole = new ApplicationRole("User", "System Contraint User");
roleManager.Create(userRole);
}
}
}
}
MyDbContext.cs
using Login.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Login.Models
{
public class MyDbContext : IdentityDbContext<ApplicationUser>
{
public MyDbContext() : base("name=LoginDBContext")
{
}
public DbSet<Categories> Categories { get; set; }
public static MyDbContext Create()
{
return new MyDbContext();
}
}
}
Я дал вам полную заявку. Я не мог решить эту проблему, упомянутую в названии этого вопроса. Когда я запускаю приложение, выдает это исключение в файле global.asasx прямо в этой строке кода, if (!roleManager.RoleExists("Admin"))
. Что вы думаете об этой проблеме?
Вы используете контекст с именем LoginDBContext
, однако ваш Контекст DB Identity называется MyDbContext
Измените третью строку Application_Start
на
MyDbContext db = new MyDbContext();