Home > Back-end >  How can I use in Task<ActionResult<IEnumerable<T>>>
How can I use in Task<ActionResult<IEnumerable<T>>>

Time:12-20

I have this function ("GetUsers") in my API:

private readonly DBCyberCaseTools _context;

public UserController(DBCyberCaseTools context)
{
    _context = context;
}

// GET: api/User
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetUsers()
{
  if (_context.Users == null)
  {
      return NotFound();
  }
    return await _context.Users.ToListAsync();
}

But I don't understand how to use it from another function?

When I call this function, I can't understand how I access the result?

(in swagger it works well)

I'm trying to call it, from function of Login: (UserConstants is just an example class, and now I would like to replace this by calling to "GetUsers".

private UserModel Authenticate(UserLogin userLogin)
{
    var currentUser = UserConstants.Users.FirstOrDefault(o => o.Username.ToLower() == userLogin.Username.ToLower() && o.Password == userLogin.Password);

    if (currentUser != null)
    {
        return currentUser;
    }

    return null;
}

Thank You

CodePudding user response:

This is not just a method, but a controller action (read more here), which usually should not be called manually but is invoked by framework (ASP.NET/ASP.NET Core) and the return value is processed by it.

The only "standard" reason to call this method directly I know is for unit testing, in this case you need to await the result of the method and process it contents:

var controller = ...; // instantiate the controller
ActionResult<IEnumerable<User>> actionResult = await controller.GetUsers();
IEnumerable<User>? users = actionResult.Value; // check users
ActionResult? result = actionResult.Result; // check set result for example: result is NotFoundResult

I'm trying to call it, from function of Login: (UserConstants is just an example class, and now I would like to replace this by calling to "GetUsers".

You should not, for multiple reasons, first of all there is no point in fetching all users when you need to find one, just write correct query (also possibly you should not store passwords in database as is, but should consider storing password hashes - see this question), secondary - action can have much more logic which is not relevant for Authenticate (for example NotFound does not seem to be a valid response, also _context.Users should not be null if _context is EF context).

  • Related