ASP.NET MVC v5、Entity Framework v7、および Identity v3 を使用して、単純なログイン システムをゼロから構築しようとしています。
私が望むのは、ユーザーがアカウントを作成し、そのアカウントがデータベースに保存されることだけです。私はそれをIdentity v2で動作させることができました。スキャフォールディングされたMVCアプリはIdentity v3を使用してデータベースを作成し、ユーザーをうまく保存するので、両方の動作中のアプリからコードを接続して新しいアプリを作成しようとしています.
これまでのコードは次のとおりです。
Startup.cs :
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
appsettings.jsonには、データベースに接続するための次のコードが含まれています。
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=SimpleAuthenticationApp;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Controllers/AccountController.csの Register POST アクションのコードは次のとおりです。
[HttpPost]
public async Task<IActionResult> Register (RegisterViewModel model)
{
try
{
var user = new ApplicationUser { UserName = model.Email };
IdentityResult result = await _userManager.CreateAsync(user, model.Password);
Console.WriteLine(result);
return View("Home", "Index");
}
catch (Exception ex)
{
Console.WriteLine(ex);
return View();
}
}
ここでは、try ブロックにブレーク ポイントを設定し、catch ブロックに入ると、例外が「カウント = 1」または「1 つ以上のエラーが発生しました」と読み取り、それらのエラーを確認する方法がわかりません。それは。
このコードでRegisterViewModel
は、Email、Password、および ConfirmPassword のフィールドを持つ単なる ViewModel です。Account/Registerビューは、これらのフィールドを要求する単なるフォームです。ApplicationUser
から拡張されたクラスですIdentityUser
。
私はここで立ち往生しています。アプリケーションでデータベースを作成し、Identity を使用してユーザー プロファイルを保存する方法を見つけたいと思います。コードのアイデア、またはエラー メッセージを確認する方法はありますか?