I am getting into ASP.NET Core 2.0 with Web API. One of my first methods are my login:
/// <summary>
/// API endpoint to login a user
/// </summary>
/// <param name="data">The login data</param>
/// <returns>Unauthorizied if the login fails, The jwt token as string if the login succeded</returns>
[AllowAnonymous]
[Route("login")]
[HttpPost]
public IActionResult Login([FromBody]LoginData data)
{
var token = _manager.ValidateCredentialsAndGenerateToken(data);
if (token == null)
{
return Unauthorized();
}
else
{
return Ok(token);
}
}
My LoginData
using DataAnnotations:
public class LoginData
{
[Required]
[MaxLength(50)]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Required]
[MaxLength(16)]
public string IpAddress { get; set; }
}
So my ModelState
is well filled automatically when the login happens and e.g. the password is empty (of course on client side there should be a validation too for it later).
What is the best way to
- check the model state,
- getting a readable string out of all errors and
- return a
BadRequest
with this error?
Of course I could write it all myself in a helper method. But I thought about a filter maybe?
ValidationAttribute
(filter) for this. At the very least, it could be inspiration for how to build something yourself. – Triforium