ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,190 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi,
How can I return customized error messages from API to client?
[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);
}
}
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
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!