question

MiroslavMakhruk-5045 avatar image
0 Votes"
MiroslavMakhruk-5045 asked MiroslavMakhruk-5045 answered

A way to have multiple ASP.NET Core Identities per app

Hi,
I'm trying to have multiple ASP.NET Core Identities per app.
For example, if I have two controllers "Login" and "Login2", I want one of them to use DB1 as IdentityDbContext while the other to use DB2.

I have these two lines at Startup.ConfigureServices:

 services.AddDbContext<IdentityDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DB1")));
 services.AddDbContext<IdentityDBContext_v2>(options => options.UseSqlServer(Configuration.GetConnectionString("DB2")));

and this one:

 services.AddIdentity<SystemUser, Role>()
  .AddEntityFrameworkStores<IdentityDBContext>() 
  .AddEntityFrameworkStores<IdentityDBContext_v2>() 
  .AddDefaultTokenProviders();

No matter what I do only the first AddEntityFrameworkStores<IdentityDBContext>() works and the DB1 is used in both controllers.
However if I put .AddEntityFrameworkStores<IdentityDBContext_v2>() as the first line then DB2 is used in both controllers.





microsoft-identity-manager
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

MiroslavMakhruk-5045 avatar image
0 Votes"
MiroslavMakhruk-5045 answered

Ok, so I've solved it "myself" (all credits to stackoverflow). Finally I've came up with this code:

 services.AddDbContext<IdentityDBContext>((serviceProvider, options) =>
     {
         var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
         var httpRequest = httpContext.Request;
         var pathParts = httpRequest.Path.Value.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
         var pathParsed = decimal.TryParse(pathParts[1], out decimal pathVersion);
         var qsParsed = decimal.TryParse(httpRequest.Query["api-version"], out decimal qsVersion);
         var useV1DB = (!pathParsed || pathVersion == 1) && (!qsParsed || qsVersion == 1);
         options.UseSqlServer(Configuration.GetConnectionString(useV1DB ? "V1DB" : "V2DB"));
   });

it allows me both to have version number as part of the path and as a querystring parameter "api-version"

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.