title: Returning error message from .NET Core Web API
body: <p>I have a .NET Core Web API controller to handle a POST request which takes a JSON ApiUser object and also returns an ApiUser object</p>
  
  <pre><code>[HttpPost]
  public ApiUser Post([FromBody] ApiUser model) {
      return new ApiUser();
  }
  </code></pre>
  
  <p>Let's say I want to return an error message to the client: <strong>"Email already exists."</strong>  <strong>I don't know how best to do it in a simple manner.</strong>  </p>
  
  <p>I could add an "ErrorMsg" property to ApiUser (and every other class that I return through the API), but not sure if this is the correct way.</p>
  
  <p>"Pre-Core", I'd throw a HttpResponseException, which is not supported in Core.  This was nice because it would create a simple JSON with "Message" which I could then grab.  (Goofy: I'd use status 202 Accepted as a flag to my client that we had a "known error".)</p>
  
  <pre><code>throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.Accepted, msg));
  </code></pre>
  
  <p>(I think I'd prefer to deal with this inside the controller, instead of "filters" or "middleware". One concern with the latter two is that if I add razor pages, I assume I'd need to know if error came from api calls or from UI web calls.)</p>
  
  <p>UPDATE #1</p>
  
  <p>Seems I can do the following (return <strong>ActionResult&lt; T></strong>) to simulate what I did before with HttpResponseException.  Still not sure if doing something like this or returning status 200 with adding ErrorMsg to ApiUser would be better.</p>
  
  <pre><code>[HttpPost]
  public async Task&lt;ActionResult&lt;ApiUser&gt;&gt; Post([FromBody] ApiUser model) {
      ...
      if (emailExists) return StatusCode(400, "Email already exists.");
      else return user;
  }
  </code></pre>