Search code examples
c#asp.net-mvcasp.net-coremodel-view-controller

Can't return Ok() , Unauthorized(), BadRequest() in my repository C# .NET core


I implemented an IUserRepository, where I implement login and registration in my UserRepository; this is my code

public async Task<IActionResult> LoginAsync([FromBody] UserCred user)
{
    var result = await _signInManager.PasswordSignInAsync(user.username, user.password, user.rememberMe, false);

    if (result.Succeeded)
    {
        var token = _jwtAuthenticationManager.Authenticate(user.username, user.password);
        if (token == null)
            return Unauthorized();
        return Ok(token);
    }
    return BadRequest();
}

However, I'm getting an error of:

The name "BadRequest" does not exist in the current context

Same for the Ok and Unauthorized.

However, I did not have this issue when I was implementing these calls directly in my userController. I suppose I can only return BadRequest in the controller? Is there any way I can overcome this since, if it's not IActionResult, how will I check if results.Succeeded?

Moreover, this is my UserController:

[HttpPost]
[AllowAnonymous]
[Route("login")]
public async Task<IActionResult> Login([FromBody] UserCred user)
{
   return await _userRepository.LoginAsync(user);
}

Solution

  • BadRequest() is a method of the controller itself.

    It's better to return a value from IUserRepository, e.g. null or token, and then in the controller map that value to Ok or BadRequest response.
    Making a decision about the response type is the responsibility of the controller itself.
    Code like this placed in the controller should do the job:

    token = await _userRepository.LoginAsync(user);
    return token == null ? BadRequest() : Ok(token);