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







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












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


Posted By  -  Karan Gupta
 
Posted On  -  Friday, March 04, 2016

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250