I am getting into ASP.NET Core 2.0 with Web API. One of my first methods are my login:
///
/// API endpoint to login a user
///
/
To check if the model state is valid use the ModelState property (exposed by the ControllerBase class which the Controller class inherits from)
ModelState.IsValid
To get the errors from the ModelState you could filter out the errors from the dictionary and return them as a list
var errors = ModelState
.Where(a => a.Value.Errors.Count > 0)
.SelectMany(x => x.Value.Errors)
.ToList();
One option is then to validate the state in every method/controller but i recommend you to implement the validation in a base class which validates the model in the
OnActionExecuting method like this
public class ApiController : Controller
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!ModelState.IsValid)
{
var errors = ModelState
.Where(a => a.Value.Errors.Count > 0)
.SelectMany(x => x.Value.Errors)
.ToList();
context.Result = new BadRequestObjectResult(errors);
}
base.OnActionExecuting(context);
}
}
Then every controller which should have automatic model state validation just inherit from the base class
public class TokenController : ApiController
{
///
/// API endpoint to login a user
///
/// The login data
/// Unauthorizied if the login fails, The jwt token as string if the login succeded
[AllowAnonymous]
[Route("login")]
[HttpPost]
public IActionResult Login([FromBody]LoginData data)
{
var token = _manager.ValidateCredentialsAndGenerateToken(data);
if (token == null)
{
return Unauthorized();
}
else
{
return Ok(token);
}
}
}