ASP.NET Web API is a framework to build APIs to provide web services for a broad range of clients. APIs are the online services that the client will use to get the data and updates.
Here, we will be talking about an example to create a Web API and call it, using a desktop client application.
Creating a new project
Start Visual Studio and go to File -> New -> Project.
In the template panel select Installed -> Templates -> Visual C# -> Web -> ASP.NET Web Application.
Write the name of the project APIs_tutorial and click OK.
A dialog prompting a new ASP.NET Project will appear. Select an empty ASP.NET template, check MVC checkbox and click OK.
Adding Model
Right click Models folder in Solution Explorer. Go to Add and select the Class.
In Add New Item dialog, write the class name Temperature and click Add.
Open Weather.cs and write the code, given below:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace APIs_tutorial.Models
- {
- public class Weather
- {
- public int id { get; set; }
-
- public string City { get; set; }
-
- public string Temperature { get; set; }
-
- public string Precipitation { get; set; }
-
- public string Humidity { get; set; }
-
- public string Wind { get; set; }
- }
- }
Adding Web API 2 Controller Right click on the Controllers folder in Solution Explorer. Go to Add and select the Controller.
On Add Scaffold dialog, select Web API 2 Controller Empty and click Add.
Write the name of the Controller; WeatherController, and click Add.
Visual Studio scaffolds a few things and makes a new API controller.
Open the WeatherController.cs file and write the following code:
- using APIs_tutorial.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
-
- namespace APIs_tutorial.Controllers
- {
- public class WeatherController : ApiController
- {
-
- public static List<Weather> reports = new List<Weather>
- {
- new Weather { id = 1, City = "Islamabad", Temperature = "25 f", Humidity = "70%", Precipitation = "0%", Wind = "15mph" },
- new Weather { id = 2, City = "Karachi", Temperature = "40 f", Humidity = "80%", Precipitation = "0%", Wind = "40mph" },
- new Weather { id = 3, City = "Lahore", Temperature = "35 f", Humidity = "50%", Precipitation = "0%", Wind = "10mph" },
- new Weather { id = 4, City = "Peshawar", Temperature = "25 f", Humidity = "65%", Precipitation = "0%", Wind = "15mph" },
- new Weather { id = 5, City = "Quetta", Temperature = "40 f", Humidity = "50%", Precipitation = "0%", Wind = "20mph" },
- };
-
- [HttpGet]
- public List<Weather> Get()
- {
- return reports;
- }
-
- [HttpGet]
- public Weather Get(int id)
- {
- return reports.Find((r) => r.id == id);
- }
-
- [HttpPost]
- public bool Post(Weather report)
- {
- try
- {
- reports.Add(report);
- return true;
- }
- catch
- {
- return false;
- }
- }
-
- [HttpDelete]
- public bool Delete(int id)
- {
- try
- {
- var itemToRemove = reports.Find((r) => r.id == id);
- reports.Remove(itemToRemove);
- return true;
- }
- catch
- {
- return false;
- }
- }
- }
- }
In this example, we have hard coded the data. In the actual scenario, the data should be fetched from the database.
You have created a Web API. Now, open Global.asax and add the following code:
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- GlobalConfiguration.Configure(WebApiConfig.Register);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- }
Now our API is ready. All we have to do is to create a client.
Creating Client
Right click on the solution in Solution Explorer. Go to Add and select New Project.
On Add new project dialog, go to Installed -> Visual C# -> Windows -> Classic Desktop and select console Application.
Write the name of the project, Weather_Report, and click OK.
Install the package Microsoft.AspNet.WebApi.Client.
To install the package, right click on the References in Solution Explorer. Select Manage NutGet Packages.
Click on the browse tab and search Microsoft.AspNet.WebApi.Client.
Select the package and click Install.
Click on I Accept on the Licence Acceptance dialog and the package will install.
Add a new class WeatherClient.
Write the following code in WeatherClient.cs:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace Weather_Report
- {
- class Program
- {
- static void Main(string[] args)
- {
- while(true)
- {
- Console.WriteLine("Enter Action:");
- string id = Console.ReadLine();
-
- GetRequest(id).Wait();
- Console.ReadKey();
- Console.Clear();
- }
- }
-
- static async Task GetRequest(string ID)
- {
- switch (ID)
- {
-
- case "Get":
- Console.WriteLine("Enter id:");
- int id = Convert.ToInt32(Console.ReadLine());
- using (var client = new HttpClient())
- {
- client.BaseAddress = new Uri("http://localhost:38104/");
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
- HttpResponseMessage response;
-
-
- if (id == 0)
- {
- response = await client.GetAsync("api/Weather");
- if (response.IsSuccessStatusCode)
- {
- WeatherClient[] reports = await response.Content.ReadAsAsync<WeatherClient[]>();
- foreach (var report in reports)
- {
- Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}", report.City, report.Temperature, report.Humidity, report.Precipitation, report.Wind);
- }
- }
- }
- else
- {
- response = await client.GetAsync("api/Weather/" + id);
- if (response.IsSuccessStatusCode)
- {
- WeatherClient report = await response.Content.ReadAsAsync<WeatherClient>();
- Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}", report.City, report.Temperature, report.Humidity, report.Precipitation, report.Wind);
- }
- }
- }
- break;
-
-
- case "Post":
- WeatherClient newReport = new WeatherClient();
- Console.WriteLine("Enter data:");
- Console.WriteLine("Enter City:");
- newReport.City = Console.ReadLine();
- Console.WriteLine("Enter Temperature:");
- newReport.Temperature = Console.ReadLine();
- Console.WriteLine("Enter Precipitation:");
- newReport.Precipitation = Console.ReadLine();
- Console.WriteLine("Enter Humidity:");
- newReport.Humidity = Console.ReadLine();
- Console.WriteLine("Enter Wind:");
- newReport.Wind = Console.ReadLine();
-
- using (var client = new HttpClient())
- {
- client.BaseAddress = new Uri("http://localhost:38104/");
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
- HttpResponseMessage response = await client.PostAsJsonAsync("api/Weather", newReport);
-
- if (response.IsSuccessStatusCode)
- {
- bool result = await response.Content.ReadAsAsync<bool>();
- if (result)
- Console.WriteLine("Report Submitted");
- else
- Console.WriteLine("An error has occurred");
- }
- }
-
- break;
-
-
- case "Delete":
- Console.WriteLine("Enter id:");
- int delete = Convert.ToInt32(Console.ReadLine());
- using (var client = new HttpClient())
- {
- client.BaseAddress = new Uri("http://localhost:38104/");
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
- HttpResponseMessage response = await client.DeleteAsync("api/Weather/" + delete);
-
- if (response.IsSuccessStatusCode)
- {
- bool result = await response.Content.ReadAsAsync<bool>();
- if (result)
- Console.WriteLine("Report Deleted");
- else
- Console.WriteLine("An error has occurred");
- }
- }
- break;
- }
-
- }
- }
- }
Use HttpClient to send the http request to the Web API we have just created. Now, let's execute the program and Get, Post and Delete some data.
Calling Web APIs First run the Web Application by pressing F5. After it, right click on the Weather_Report console Application we have just created. Go to Debug and select Start new instance.
Let's send a request to get all the reports.
Try sending a GET request to get a specific report.
Try POST request and add some data.
Now, check if the data is really submitted or not.
The data is submitted. Now, send a delete request.
Check if the data is deleted or not.
Now, we have a working Web API.