jmk22
jmk22

Reputation: 1164

User registration using ASP.NET Identity v3 - users and database are not created

I am trying to build a simple login system from the ground up, using ASP.NET MVC v5, Entity Framework v7, and Identity v3.

All I want is for the user to create an account, and for that account to be saved in a database. I was able to get it working with Identity v2, and the scaffolded MVC app uses Identity v3 to create a database and save users just fine, so I'm trying to connect the code from both working apps to make a new one.

Here's the code I have so far:

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 contains this code for the connection to the database:

"Data": {
  "DefaultConnection": {
    "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=SimpleAuthenticationApp;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Here's the code for the Register POST action in Controllers/AccountController.cs:

    [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();
        }
    }

Here, I set a break point at the try block, and when it enters the catch block, the exceptions reads "Count=1", or "One or more errors occurred", and I'm not sure how to see what those errors are.

In this code, RegisterViewModel is just a ViewModel with fields for Email, Password, and ConfirmPassword. The Account/Register view is just a form that asks for these fields. ApplicationUser is a class that extends from IdentityUser.

I'm stuck here, and I'd like to figure out how to get the app to create a database and save user profiles in it using Identity. Any ideas for the code, or how to see what the error messages are?

Upvotes: 1

Views: 919

Answers (1)

Lukasz Mk
Lukasz Mk

Reputation: 7350

I'd like to figure out how to get the app to create a database and save user profiles in it using Identity.

As far I know database is not created automatically during user registration process, so you need have updated db before.

You can create db yourself or you can use DB initializers.

Remember - if you use Code-First approach - that you need apply all migrations before lunching app

Console command in VS2015 RC1: dnx ef database update

All I want is for the user to create an account, and for that account to be saved in a database. I was able to get it working with Identity v2, and the scaffolded MVC app uses Identity v3 to create a database and save users just fine, so I'm trying to connect the code from both working apps to make a new one.

Maybe starting form latest code will be better way then connecting old and new ? Try create new Project with default implementation - it's works fine for me, and then you can extend default solution as you want :)

More about Authentication and Authorization.

Here, I set a break point at the try block, and when it enters the catch block, the exceptions reads "Count=1", or "One or more errors occurred", and I'm not sure how to see what those errors are.

Use ex.ToString() method - this give you full stack information about exception and all inner exceptions.

Upvotes: 1

Related Questions