ObjectDisposedException when creating user

670 views Asked by At

I'm getting an error when I try to create a user. I got it at line 15 in the following code.

1  public async void AddOrganisationAdmin()
2    {
3        
4        String OrganisationName = Request["OrganisationName"];
5        Debug.Print(OrganisationName);
6        RegisterViewModel model = new RegisterViewModel();
7        model.Email = "admin@" + OrganisationName;
8        model.Organisation = OrganisationName;
9        model.Password = "adminPassword!1";
10       model.ConfirmPassword = "adminPassword!1";
11       model.Role = "Organisation Administrator";
12
13
14       var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, Organisation = model.Organisation, Role = model.Role };
15       IdentityResult result = await UserManager.CreateAsync(user, model.Password);
16   }

The error is:

An exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll but 
was not handled in user code

Additional information: Cannot access a disposed object.

What object is disposed? These lines are a copy of the default register function in a asp.net mvc 5 project, so what am I doing wrong?

I'm calling the function from an ajax post like this:

$.ajax({
      url: "/Account/AddOrganisationAdmin",
      type: 'POST',
      data: { OrganisationName : "@CompanyName"},
      success: function (data, textStatus, xhr) {
             console.log(data);
      },
      error: function (xhr, textStatus, errorThrown) {
             console.log(xhr);
      }
});

I get into the function and I have the correct name.

1

There are 1 answers

0
Gert Kommer On BEST ANSWER

The comment of tacos_tacos_tacos made me look into dbcontext a bit and after a trail and error period I got the following

1    public void AddOrganisationAdmin()
2    {
3        
4        String OrganisationName = Request["OrganisationName"];
5        Debug.Print(OrganisationName);
6        RegisterViewModel model = new RegisterViewModel();
7        model.Email = "admin@" + OrganisationName + ".com";
8        model.Organisation = OrganisationName;
9        model.Password = "adminPassword!1";
10       model.ConfirmPassword = "adminPassword!1";
11       model.Role = "Organisation Admin";
12       Promato.Models.ApplicationDbContext dbcontext = new Promato.Models.ApplicationDbContext();
13        
14       var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, Organisation = model.Organisation, Role = model.Role };
15       user.PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password);
16       user.SecurityStamp = Guid.NewGuid().ToString();
17       dbcontext.Users.Add(user);
18       dbcontext.SaveChanges();
19   }

This code is working for me. A user is added to the .mdf and I can login:)