return customized error messages from api to client

tinac99 1 Reputation point
2021-09-08T13:18:03.767+00:00

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

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,190 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. tinac99 1 Reputation point
    2021-09-08T13:28:44.437+00:00

    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!