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.
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 ");
}
}
Your problem is that you are expecting a type of Taskcs
in your controller but you are sending a type of Employee
:
[HttpPost]
public IHttpActionResult AddTask([FromBody] Taskcs css) <-- expects Taskcs
In your client:
HttpResponseMessage responseMessage = await client.PostAsJsonAsync("api/values/AddTask",
emp); <-- emp is an Employee
So there are two options:
public IHttpActionResult AddTask([FromBody] Employee css)
HttpResponseMessage responseMessage = await client.PostAsJsonAsync("api/values/AddTask",
emp.Task);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.