Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a query that how can i post data using web Api in winforms application. Currently it giving me error which is below . I check web api using Postman App. It's working fine.But when i post data using winforms it returning me status code 200 and data is not inserting in database.Any help will be appreciated.


What I have tried:

winforms button click event

       private void button1_Click(object sender, EventArgs e)
        {
        try
        {
            EmployeeClass emp = new EmployeeClass() { Project_Name = "Hello",
             Task = "Task", Username 
              = "fazal" };
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://localhost:44342/");
            HttpResponseMessage responseMessage = 
            client.PostAsJsonAsync("api/values/AddTask", 
           emp).Result;
            }
            catch (Exception ex)
             {

            MessageBox.Show(ex.Message);
            }
       
        }


Here is return

{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{ Pragma: no-cache X-SourceFiles: =?UTF-8?B?


The Web Api controller Code is

    database_access_layer.db dblayer = new database_access_layer.db();

    [HttpPost]

    public IHttpActionResult AddTask([FromBody] Taskcs css)
    { 
        try
        {
          dblayer.AddTask(css);
            return Ok("Success");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return Ok("Something not OK ");
        }

    }
Posted
Updated 12-Jan-21 22:22pm
Comments
Sandeep Mewara 13-Jan-21 1:14am    
I don't see an error response. 200-OK is expected one.
Member 14852747 13-Jan-21 1:45am    
it is respone that i return.Actually data is not inserting in database with post request

1 solution

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:
C#
[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:
C#
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[^]
C#
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);
    }
}
 
Share this answer
 
Comments
Member 14852747 14-Jan-21 3:16am    
did not solve my problem
Richard Deeming 14-Jan-21 4:11am    
It won't solve the problem with the data not inserting. But you can't fix that until you know what the problem is. And at the moment, you're just throwing the details of the problem away and returning "OK" for all requests.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900