Home > front end >  Can't return Ok() , Unauthorized(), BadRequest() in repository c# .net core
Can't return Ok() , Unauthorized(), BadRequest() in repository c# .net core

Time:08-25

I implemented a IUserRepository where I implement login and register, 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 im getting an error of

The name of "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?, however is there any way I can overcome this since if its not IActionResult how will i check if results.Succeeded? –

Moreover this is my UseController

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

CodePudding user response:

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);

CodePudding user response:

It is possible by returning EG.

new BadRequestObjectResult("some error");

But, you shouldn't be doing anything web related in a repository!

Instead you should throw an appropriate exception from your repository and catch it in the controller. Then, when you catch the exception, return BadRequest from there.

Also, be sure you are returning the correct response.

BadRequest means there was something wrong with the request - maybe the username or password was null, etc. This should be checked before even attempting to hit the repository.

Unauthorized may be a better response if authentication fails.

Then, if there is genuinely an error, don't hide it, it will cause problems later when you have lots of endpoints you can't debug, return a 500 response (but don't include the exception details in production)

  • Related