title: return errors from web api 2 account register
body: <p>I am trying to use the account controller in the MVC project to call the register account method in a WebApi 2 account controller. All works fine but I cant figure out how to return errors back to the MVC project such as: "password must contain Upper case and lower case" etc.</p>
  
  <p>ASP.NET MVC account controller register:</p>
  
  <pre><code>//
      // POST: /Account/Register
      [HttpPost]
      [AllowAnonymous]
      [ValidateAntiForgeryToken]
      public async Task&lt;ActionResult&gt; Register(RegisterViewModel model)
      {
          if (ModelState.IsValid)
          {
              var response =
              await
                  ApiRequest.PostAsync(String.Format("{0}/api/v1/account/register", "http://localhost:12345"), model);
  
              if (response.IsSuccessStatusCode)
              {
                  return RedirectToAction("Index", "Home");
  
              }
              // Add errors
  
          }
  
          // If we got this far, something failed, redisplay form
          return View(model);
      }
  </code></pre>
  
  <p>ApiRequest class:</p>
  
  <pre><code>public static class ApiRequest
  {
      public static async Task&lt;HttpResponseMessage&gt; PostAsync(string uri, object item)
      {
          StringContent content = new StringContent(await Json.SerializeAsync(item));
          content.Headers.ContentType = new MediaTypeHeaderValue("text/json");
  
          using (var client = new HttpClient())
          {
              client.DefaultRequestHeaders.Accept.Clear();
              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  
              return await client.PostAsync(new Uri(uri), content);
          }
      }
  
      public static async Task&lt;HttpResponseMessage&gt; GetAsync(string uri)
      {
          using (var client = new HttpClient())
          {
              client.DefaultRequestHeaders.Accept.Clear();
              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  
              return await client.GetAsync(new Uri(uri));
          }
      }
  
      public static async Task&lt;HttpResponseMessage&gt; PutAsync(string uri, object item)
      {
          StringContent content = new StringContent(await Json.SerializeAsync(item));
          content.Headers.ContentType = new MediaTypeHeaderValue("text/json");
  
          using (var client = new HttpClient())
          {
              client.DefaultRequestHeaders.Accept.Clear();
              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  
              return await client.PutAsync(new Uri(uri), content);
          }
      }
  
      public static async Task&lt;HttpResponseMessage&gt; DeleteAsync(string uri, object id)
      {
          using (var client = new HttpClient())
          {
              client.DefaultRequestHeaders.Accept.Clear();
              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  
              return await client.DeleteAsync(new Uri(String.Format("{0}/{1}", uri, id)));
          }
      }
  }
  
  public static class HttpResponseMessageExtensions
  {
      public static async Task&lt;T&gt; DeserialiseContentAsync&lt;T&gt;(this HttpResponseMessage message)
          where T : class
      {
  
          return await Json.DeserialiseAsync&lt;T&gt;(await message.Content.ReadAsStringAsync());
      }
  }
  </code></pre>
  
  <p>Web API 2 account controller register:</p>
  
  <pre><code>//
      // POST: /Account/Register
      [AllowAnonymous]
      [Route("Register")]
      [HttpPost]
      public async Task&lt;IHttpActionResult&gt; Register(RegisterViewModel model)
      {
          if (!ModelState.IsValid)
          {
              return BadRequest(ModelState);
          }
  
          var user = new ApplicationUser
          {
              UserName = model.Username,
              Email = model.Email,
              FirstName = model.FirstName,
              LastName = model.LastName
          };
  
          IdentityResult result = await UserManager.CreateAsync(user, model.Password);
  
          if (!result.Succeeded)
          {
              if (result.Errors != null)
              {
                  foreach (string error in result.Errors)
                  {
                      ModelState.AddModelError("", error);
                  }
                  return BadRequest(ModelState);
              }
  
              return BadRequest();
          }
  
          // Send email verification
          //string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
  
          //var callbackUrl = new Uri(Url.Link("ConfirmEmail", new { userId = user.Id, code = code }));
  
          //await
          //    UserManager.SendEmailAsync(user.Id, "Confirm your account",
          //        "Please confirm your account by clicking &lt;a href=\"" + callbackUrl + "\"&gt;here&lt;/a&gt;");
  
          Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));
  
          return Created(locationHeader, user);
      }
  </code></pre>
  
  <p>GetErrorResult code:</p>
  
  <pre><code>private IHttpActionResult GetErrorResult(IdentityResult result)
      {
          if (result == null)
          {
              return InternalServerError();
          }
  
          if (!result.Succeeded)
          {
              if (result.Errors != null)
              {
                  AddErrors(result);
              }
  
              if (ModelState.IsValid)
              {
                  // No ModelState errors are available to send, so just return an empty BadRequest.
                  return BadRequest();
              }
  
              return BadRequest(ModelState);
          }
  
          return null;
      }
  
      private void AddErrors(IdentityResult result)
      {
          foreach (string error in result.Errors)
          {
              ModelState.AddModelError("", error);
          }
      }
  </code></pre>
  
  <p>Im new to MVC and WebApi and have mainly been following tutorials, this is assume is basic stuff but i cant find a solution anywhere. I have separated the WebApi from the project intentionally so I can learn how these processes work better.</p>
  
  <p>I'd like the solution not to be in javascript.</p>
  
  <p>I'm assuming all subsequent requests will need to have a bearer token attached to the httpclient but i think this will be in another question.</p>
  
  <p>Thanks in advance for any help on this</p>