Reputation: 439
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");
}
}
Upvotes: 4
Views: 4780
Reputation: 1170
One of the simplest ways
return StatusCode(StatusCodes.Status401Unauthorized, new { message = "Invalid username or password" });
Upvotes: 7