0

I have the following Web API 2.0 call:

 [System.Web.Http.Route("api/createuser")]
 [System.Web.Http.HttpPost]
 public async Task<IHttpActionResult> CreateUser([FromBody] WDUser value)
 {
     var user = value;

     if (string.IsNullOrEmpty(user.Email))
     {
         throw new ProcessException($"Email is blank.");                
     }
     return Ok("all good");
 }

The ProcessException is straight forward:

internal class ProcessException : Exception
{
    public ProcessException()
    {
    }

    public ProcessException(string message) : base(message)
    {
    }
 }

I call my api like so:

  using (var client = new HttpClient())
  {
      client.BaseAddress = new Uri("http://localhost:49352/");
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


      var departmentPost = new WDUser() { Email= "" };
      HttpResponseMessage responsePost = client.PostAsJsonAsync("api/createuser", departmentPost).Result;
      if (responsePost.IsSuccessStatusCode)
      {
          // Get the URI of the created resource.
          Uri returnUrl = responsePost.Headers.Location;
          Console.WriteLine(returnUrl);
      }
  }

If I supply an email, the API returns ok. As you can see, I intentionally left the email blank. I make the API call and an error is returned, but I cannot find the message "Email is blank"
How do I retrieve the error message being returned fro the API?

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
BoundForGlory
  • 4,114
  • 15
  • 54
  • 81
  • 1
    [this answer](https://stackoverflow.com/a/15205478/2788979) may be helpful. You may need to await your response, and read content from it. – farzaaaan Oct 03 '17 at 14:20

1 Answers1

1

Try this:

if (responsePost.IsSuccessStatusCode)
{
     // Get the URI of the created resource.
     Uri returnUrl = responsePost.Headers.Location;
     Console.WriteLine(returnUrl);
}
else
{
    string content = response.Content.ReadAsStringAsync().Result;
    Console.WriteLine(content);
}
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116