MVC Web API and ASP.NET Identity – Changing Identity Database Connection

12 03 2014

Sometimes simple things are hard, or at least hard to find.
I have created a Web API and added ASP.NET Identity for user management.

This works well, if one uses the project template, not so well if you want to add ASP.NET Identity at at a later point of time. Therefore just remember it, when creating the project.
However, I did not want to use the preset standard localdb database file  in my application. I was looking where to change the identity database context.
It was obvious that the presets use the “DefaultConnection” connection string in web.config and it works, if you rename the database there, but sometimes I am a bit picky and I wanted to name this special connection differently: “IdentityConnection”.

It really took my a while, because all my searches for DBContext and IdentityDBContext were in vain.
I drilled in deeper and ended up in the Startup.Auth.cs file in the Startup folder of my solution.
Here the user store gets initialized with this line of code:

UserManagerFactory = () 
=> new UserManager<IdentityUser>(new UserStore<IdentityUser>()));

This is the place to change the identity connection string!

One needs to use a different overload of the store’s constructor passing in a new IdentityContext created with the new db connection. Such as this:

UserManagerFactory = () => new UserManager<IdentityUser>
(new UserStore<IdentityUser>(new IdentityDbContext("IdentityConnection")));

And yes, the new “IdentityConnection” connection needs to be configured in Web.Config, of course.

After this, the Identity tables get created in the new database, as specified.

This should not be so hard to find. Maybe the Web API developers have some time to put in a comment in Startup.Auth.cs about db configuration, in the next version.







Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: