Status code
200
means the request succeeded. But that's expected, since you always return
Ok
, even if an error occurs.
Change your API method to return a more appropriate response when an exception is thrown. For example:
[HttpPost]
public IHttpActionResult AddTask([FromBody] Taskcs task)
{
try
{
dblayer.AddTask(task);
return Ok();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
NB: If there are specific exceptions which you know your
AddTask
might throw, you might want to handle them differently. For example:
catch (DuplicateKeyException ex)
{
return Conflict();
}
catch (ValidationFailedException ex)
{
return BadRequest(ex.Message);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
NB 2: Your client code is currently blocking the UI waiting for the request to complete. You should avoid using this sort of sync-over-async approach, since it could lead to your application hanging.
Should I expose synchronous wrappers for asynchronous methods? | .NET Parallel Programming[
^]
private void button1_Click(object sender, EventArgs e)
{
_ = AddEmployeeAsync();
}
private async Task AddEmployeeAsync()
{
try
{
EmployeeClass emp = new EmployeeClass
{
Project_Name = "Hello",
Task = "Task",
Username = "fazal"
};
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44342/");
using (HttpResponseMessage response = await client.PostAsJsonAsync("api/values/AddTask", emp))
{
response.EnsureSuccessStatusCode();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}