4

I am writing a web api using dot net core. The functionality is simple when users enter and invalid username or password I want to return, invalid username or password as a json response. How can I do this in dot net core, I have managed to return this

Invalid username or password

How can I return this instead

{ "message": "Invalid Login credentials!" }

this is my controller

  [HttpPost]
            [Route("/api/[controller]/signin")]
            public async Task<IActionResult> Login([FromBody] LoginViewModel loginmodel)
            {
                if (!ModelState.IsValid)
                {
                    //return BadRequestModelState();
                    return Conflict(new ErrorViewModel("Wrong data sent"));
                }
    
    
                Users user = await _userService.GetByEmail(loginmodel.Username);
                if (user == null)
                {
                   
                    return this.StatusCode(StatusCodes.Status401Unauthorized, "Invalid username or password");
                }
    
                bool isCorrectPassword = _passwordHasher.VerifyPassword(loginmodel.Password, user.Password);
                if (!isCorrectPassword)
                {
                    return this.StatusCode(StatusCodes.Status401Unauthorized, "Invalid username or password");
                }
}

1 Answer 1

7

One of the simplest ways

return StatusCode(StatusCodes.Status401Unauthorized, new { message = "Invalid username or password" });
Sign up to request clarification or add additional context in comments.

1 Comment

How are you able to read the message string on the client when handling the response in JS?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.