In this post, we will see how to resolve How to implement ASP.NET Core Web API Basic Authentication using SQL Server database without Entity Framework
Question:
In my ASP.NET Core Web API I have a basic authentication handler defined inBasicAuthenticationHandler.cs
like this:IUserRepository
is this:User.cs
:UserRepository
:Program.cs
, I have this:List<User>
to be filled from a database table, without using Entity Framework.I have an
appsettings.json
file containing this connection string:DbContext
descendent. Nor do I want one.What I want to do, at some point in
Program.cs
, is load the records from the Users.dbo.UserList
table into the List<User>
property of the UserRepository
instead of using the locally initialised version, but I just can’t seem to work out the dependency injections, the scopes, or the initialisations for it to work.EDIT 31/3
Based on Jerry’s answer, I updated
UserRepository.cs
to this:UserRepository
is called for every API request, which is a lot of database activity when the API is in heavy use.What I intend to do is have a single API method for generating a token that uses Basic Authentication, and for all other methods to use Bearer Token Authentication instead. The token will have a set lifetime, after which Basic Authentication has to be used again to create a new token.
Best Answer:
You can change theUserRepository.cs
like below. It reads the database without efcore and initialize the value of _user
in construct function.
If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com