0

I'm getting a 500 Internal Server error when trying to register a new user with ASP.net's built in user authentication.

This was previously working for me, but now I've attempted to add a FirstName and LastName field to the 'AspNetUser' table and I'm receiving the 500 error.

In my app.js I'm using angular to communicate with my c sharp controllers. I've put comments with "**" next to all the code I added since the app was registering users properly.

Previously I only registered users with an email, password, and confirmPassword. When trying to add in the FirstName and LastName, I get the 500 error.

JS:

$http.post(API_END_POINT + '/api/Account/Register', user);  //**added to post the new user. this call is triggered when a header is clicked in my html

var user = {
    Email: 'Joe@gmail.com',
    Password: 'Pass1234!',
    ConfirmPassword: 'Pass1234!',
    FirstName: 'Joe',       ///**added FirstName and LastName to test JS object
    LastName: 'Schmo'       ///**
}

AccountController

    //[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{

        // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register/")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName}; //**added FirstName and LastName to ApplicationUser

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        return Ok();
    }

}

IdentityModels.cs

I tried to follow the advice of /u/dima from this accepted answer as well as /u/ Alex Polyankin in the question I posted earlier today by adding the FirstName and LastName properties to ApplicationUser.

    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
    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 string FirstName { get; set; }     //**added these per user Dima's suggestion
    public string LastName { get; set; }      //**

}

AccountBindingModels.cs

 public class RegisterBindingModel
{
    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    [Required]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }     //**added FirstName to  account binding class

    [Required]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }       //**added FirstName to  account binding class

}

Again, I commented with ** on all the code I added since it was working.

When debugging, the user(with first and last name) appears to make it to the controller properly

However this is as far as I make it in the debugger. I get the 500 error before entering that last if statement in the account controller.

And here is the actual error in the debugger.

What might be causing this error?

Thank you very much for your time. Let me know if you need any additional information or if I am being unclear.

Community
  • 1
  • 1
user95227
  • 1,853
  • 2
  • 18
  • 36
  • what is the actual error though? the one you provided from browser console is not helping. Click on that `http://localhost:64201` link, it should go to the network tab in chrome, click again and see what the response is and what kind of error it is. – dima Jun 24 '15 at 19:36
  • @dima thank you so much for reaching out. I'm pretty new so I didn't think to look there! The error message read `ExceptionMessage: "The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database`. So I opened the package manager console and executed the `Update-Database` command but got `No pending explicit migrations.` and still encounter the same error. Is `Update-Database` what I should be executing to do the migrations? Thank you! – user95227 Jun 24 '15 at 19:43
  • @dima I also came across the top answer to [this post](http://stackoverflow.com/questions/22407968/internal-server-error-api-account-register) where someone was getting the same error as myself at the same line of code. His issue seemed to be his connection string. I checked my `web.config` and everything looks as right as I could expect. I have a connection string for the table with my models' data and one for my asp users. – user95227 Jun 24 '15 at 19:54
  • ok so really the problem is that your migrations don't work or don't update your DB. It's hard to know what the problem can be. It's been awhile since I used migrations but I think you need to specifically add a migration first and then update DB unless you have automatic migrations on. Hard to say without looking at your code. – dima Jun 24 '15 at 19:57

1 Answers1

2

From the comments above, it is clearly a db migration error. Code for package manager console:

enable-migrations
add-migration InitialCreate
update-database

More info with example here.

ranquild
  • 1,799
  • 1
  • 16
  • 25
  • After running the first two, [here is the output](http://i.imgur.com/wqEkbLY.png). I know I had entered `enable-migrations` and `update-database` previously. I had never tried `add-migration InitialCreate` before. If you're wondering why I specified the project name for `enable migrations`, it's because there are two projects in this solution and it asked me to specify. Should I try `enable-migrations force` to overwrite the existing migrations? Thanks! – user95227 Jun 24 '15 at 20:43
  • Additionally, here is my migrations folder that currently exists: http://i.imgur.com/NsKj8Dc.png – user95227 Jun 24 '15 at 20:51
  • Not sure why I didn't just try to run `update-database` after the first two commands the first time. But I did and got [this result](http://i.imgur.com/7NRv1Uk.png). Unfortunatley, I still get the same 500 server error. Please advise. Thank you so much for helping! – user95227 Jun 24 '15 at 21:00
  • It appears to be the same. [ExceptionMessage: "The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database](http://i.imgur.com/JeHUcaH.png). I really appreciate you looking into this. I can try removing the current migrations folder and enabling them again or just force another add. I'll be sure to commit the current state of the project so I can revert if I break things. Let me know if you have any ideas. Thanks Alex! – user95227 Jun 25 '15 at 12:48
  • 1
    If possible, delete entire database in development environment, delete migrations and let ef recreate database from scratch. – ranquild Jun 25 '15 at 12:50
  • [Ok check it out](http://i.imgur.com/AAmP2XI.png)! `FirstName` and `LastName` were added to my table `AspNetUsers` table! Thank you so much! Now I'm left with a couple questions. As you can see from the image, I still have two DbContexts. Should I be trying to move the tables that EF created from my models to the same context as `AspNetUsers`? – user95227 Jun 25 '15 at 14:58
  • 1
    You can inherit your context from IdentityContext. – ranquild Jun 25 '15 at 14:59
  • I also noticed that my `Configuration.cs` in my Migrations folder now applies to the context with `AspNetUsers` (DefaultConnection at the top of image from last comment). So the seed method no longer can populate the tables for my created models (because they are in the other DbContext). Is there a way to get a second `Configuration.cs` file or a `Seed` method? So that I can seed both? This is a moot point if the answer to my previous comment is "Add the tables EF generated for your models to the same DbContext as `AspNetUsers`. Thanks! – user95227 Jun 25 '15 at 15:03
  • Ok so the context is for my models currently starts with `public class TourneyTimeAPIContext : DbContext`. Is this where I should change it to be `public class TourneyTimeAPIContext : IdentityDbContext` ? What will this do for me? Sorry I'm unfamiliar with this process. Thanks – user95227 Jun 25 '15 at 15:18
  • If you inherit from IdentityDbContext you will get access to Users and related tables. – ranquild Jun 25 '15 at 15:57