Description
I created a brand new .net8.0 API project in Visual Studio 2022.
Added the .Net Core Identity support with custom User MyAppUser
and Role MyAppRole
classes.
I added the DbContext
class like below
public class SchoolContext : IdentityDbContext<MyAppUser, MyAppRole, Guid>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public SchoolContext(DbContextOptions<SchoolContext> options, IHttpContextAccessor httpContextAccessor) : base(options)
{
_httpContextAccessor = httpContextAccessor;
}
.....
}
Inside a sample AuthController
, I added an Authenticate
action. Sample code snippet is given below
public class AuthController : ControllerBase
{
private readonly UserManager<MyAppUser> _userManager;
public AuthController(UserManager<MyAppUser> userManager)
{
_userManager = userManager;
}
[HttpPost("Login")]
public async Task<ApiResponse> Authenticate([FromBody] LoginUserRequest model)
{
try
{
var user = _userManager.Users.FirstOrDefault(u => u.Email == model.Email);
if (user == null)
{
throw new ApiException("Invalid Credentials", 400);
}
.............................
}
catch (Exception ex)
{
.......
}
}
}
Upto this point calling the Authenticate
action works fine.
Now, I installed the Finbuckle.MultiTenant.AspNetCore
and Finbuckle.MultiTenant.EntityFrameworkCore
packages.
In the Program.cs
added below lines of code
builder.Services.AddMultiTenant<TenantInfo>()
.WithPerTenantAuthentication()
.WithHostStrategy()
.WithConfigurationStore();
and at the end
........
app.UseMultiTenant();
.........
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Also added the [MultiTenant]
attribute to the MyAppUser
and MyAppRole
classes. Finally, inherited the DbContext class from MultiTenantIdentityDbContext
. Created and applied the migration and ran the application.
Invoking the same Authenticate
action, throws NullReferenceException at var user = _userManager.Users.FirstOrDefault(u => u.Email == model.Email);
Stack trace is given below:
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Collections.Generic.IEnumerable<TEntity>.GetEnumerator()
at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
at System.Linq.SystemCore_EnumerableDebugView`1.get_Items()
The problem persists even if the custom User
and Role
classes are not used.
Activity