Articles → ASP .NET WEB API → Call Web API Put And Post Using C#
Call Web API Put And Post Using C#
Software Requirements
Prerequisite Technical Knowledge
- The reader should have good knowledge of .net framework, visual studio, web API and C#.
- What are HTTP methods like get, put, post and what is the purpose of each method?
Create Web API Application
using System.Web.Http;
using System.IO;
namespace SampleWebAPI.Controllers {
public class Employee {
public string Name {
get;
set;
}
public string EmployeeId {
get;
set;
}
}
public class PassParamController: ApiController { [HttpPost]
public void InsertData([FromBody] string data) {
File.WriteAllText(@"c:\temp\InsertData.txt", data);
}
[HttpPut]
public void InsertDataForEmployee([FromBody] Employee data) {
File.WriteAllText(@"c:\temp\InsertDataForEmployee.txt", string.Format("Name:{0}; EmployeeId: {1}", data.Name, data.EmployeeId));
}
}
}
Create A Console Application
- System.Net.Http
- System.Net.Http.Formatting
using System;
using System.Net.Http;
Console.WriteLine("Please enter some text here:");
string data = Console.ReadLine();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:40003/");
var response = client.PostAsJsonAsync("api/PassParam", data).Result;
if (response.IsSuccessStatusCode) {
Console.WriteLine("Web API called successfully");
}
else
Console.WriteLine("There is some issue.");
Click to Enlarge
Console.WriteLine("Please enter Name:");
string name = Console.ReadLine();
Console.WriteLine("Please enter EmployeeId:");
string employeeId = Console.ReadLine();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:40003/");
var response = client.PutAsJsonAsync("api/PassParam", new Employee() {
Name = name,
EmployeeId = employeeId
}).Result;
if (response.IsSuccessStatusCode) {
Console.WriteLine("Web API called successfully");
}
else
Console.WriteLine("There is some issue.");
Click to Enlarge