question

tinac99-8590 avatar image
0 Votes"
tinac99-8590 asked AgaveJoe edited

return customized error messages from api to client

Hi,

How can I return customized error messages from API to client?


API


     [Route("Put")]
     [HttpPost]
     public IActionResult Put(CustomerDTO dto)
     {
         try
         {

             if (!ModelState.IsValid)
                 return BadRequest("Invalid data.");

             CustomerDTO dtoEdit = CustomerBusiness.Edit(dto);
             if (dtoEdit == null)
                 return NotFound();

             return Ok(dtoEdit);

         }
         catch (Exception e)
         {
             string sInnerExcpetion = string.Empty;
             if (e.InnerException != null)
                 sInnerExcpetion = e.InnerException.Message;

             ModelState.AddModelError("ErrorMessage", sInnerExcpetion);

             return BadRequest(ModelState);
         }
  }

Client


        string smsg = String.Empty;
         string res = "";
         string baseurl = "http://localhost:58567/api/Customer/Put";
         HttpClient _client = new HttpClient();


         string JsonParm = JsonConvert.SerializeObject(dto);
         StringContent ContentParm = new StringContent(JsonParm, Encoding.UTF8, "application/json");


        var response = _client.PostAsync(baseurl, ContentParm).Result;


How can I get the ErrorMessage from ModelState in API from the client?

I appreciate your help!


Thanks,

tinac99

dotnet-aspnet-core-webapi
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

tinac99-8590 avatar image
0 Votes"
tinac99-8590 answered AgaveJoe edited

I got it.


             using (HttpContent content = response.Content)
             {
                 // ... Read the string.
                 Task<string> result = content.ReadAsStringAsync();
                 res = result.Result;
                 int length = res.Length;
             }

let me know if you have other ideas.

Thanks!

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The official docs cover standard HttpClient to Web API patterns. You really should use standard async/await patterns too.

Call a Web API From a .NET Client (C#)


0 Votes 0 ·