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


  1. The reader should have good knowledge of .net framework, visual studio, web API and C#.
  2. 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






  1. System.Net.Http
  2. 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.");




Picture showing the output of calling the post method of web API using the console application
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.");




Picture showing the output of calling the put method of web API using the console application
Click to Enlarge


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

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250