title: How to do model validation in every method in ASP.NET Core Web API?
body: <p>I am getting into ASP.NET Core 2.0 with Web API. One of my first methods are my login:</p>
  <pre><code>/// &lt;summary&gt;
  /// API endpoint to login a user
  /// &lt;/summary&gt;
  /// &lt;param name=&quot;data&quot;&gt;The login data&lt;/param&gt;
  /// &lt;returns&gt;Unauthorizied if the login fails, The jwt token as string if the login succeded&lt;/returns&gt;
  [AllowAnonymous]
  [Route(&quot;login&quot;)]
  [HttpPost]
  public IActionResult Login([FromBody]LoginData data)
  {
      var token = _manager.ValidateCredentialsAndGenerateToken(data);
      if (token == null)
      {
          return Unauthorized();
      }
      else
      {
          return Ok(token);
      }
  }
  </code></pre>
  <p>My <code>LoginData</code> using DataAnnotations:</p>
  <pre><code>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; }
  }
  </code></pre>
  <p>So my <code>ModelState</code> 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).</p>
  <p>What is the best way to</p>
  <ul>
  <li>check the model state,</li>
  <li>getting a readable string out of all errors and</li>
  <li>return a <code>BadRequest</code> with this error?</li>
  </ul>
  <p>Of course I could write it all myself in a helper method. But I thought about a filter maybe?</p>