Home > Blockchain >  Get data from a table after having closed the session
Get data from a table after having closed the session

Time:05-06

In this moment I´m try to get a List of users and checks if the user is in the BD or not

I´m using Web API Net 6 and Sql Server

This is the code

        [HttpPost("login")]
        public async Task<ActionResult<string>> Login(LoginDto request)
        {
            //In this line I´m try to get the list of users (this bottom line doesn't work)
            await _context.Users.ToListAsync();

            if(user.UserName != request.UserName)
            {
                return BadRequest("User Not Found");
            }
       // ...

Here the problem is that the program has been running for 1 time until it works normally but when I end the session and come back again there is an application on the 2nd time it can no longer find the user in the database. My idea then is to add that line of code that just doesn't work (I don't know if it's due to await or if it's wrong to get through ListAsync() or if it's due to the user inside the if not being connected with the _context of the database )

By the way, that user is static having declared it like this -> public static User user = new User();

Can anyone help me with this problem or tell me better solutions on how to get data from a table

CodePudding user response:

If you just want to search your Users table for a user record with the name passed in the LoginDTO instance, then you just ask it to the database context to search for that name.

var userInDb = await _context.Users.FirstOrDefaultAsync(x => x.UserName == request.UserName);
if(userInDb == null)
   ... not found ....

But let me understand better your problem. If you are implementing your custom authorization and verification infrastructure for users, then think twice becase is not as simple as it looks. (For example, how do you store passwords in that table?) There is a dedicated library for that from Microsoft and is called ASP.NET Identity

  • Related