Author avatar

Afzaal Ahmad Zeeshan

Building and Connecting ASP.NET Web API for IoT

Afzaal Ahmad Zeeshan

  • Sep 19, 2018
  • 7 Min read
  • Sep 19, 2018
  • 7 Min read


This guide is for you, if you are:

  1. An IoT developer or work with IoT folks to provide communication support for the connected devices
  2. Interested in building web services for devices
  3. An ASP.NET developer
  4. Anyone else who wants to build a native HTTP web service

My goal in this guide is to convince you to at least consider using ASP.NET Web API as the main framework for programming web services for the IoT-connected devices.

Read my previous guide, Performance of ASP.NET Web API for IoT, for more information about performance.

Building a Small Web Service

ASP.NET Web API controllers are used to target and control how the URL mapping is performed to provide results and responses to clients.

To create a new Controller, we use the System.Web.Http.ApiController class as the base class for the object. Later, the HTTP verb functions are set for that route. Routing is set using the Route attribute of ASP.NET Web API framework. The rest is based on C# programming, to return the values from the functions and accept values to the functions as parameters.

1// Add the namespace imports
2namespace Sample {
4  // Add the route attribute, this would be accessible at: localhost:12345/api/microcontrollers/
5  [Route("api/microcontrollers")]
6  public class MicroControllers : ApiController { // Note the inheritance
7    // Adding the HTTP helpers
8    public string Get() {
9      return "Hello, world!";
10    }
12    [Route("api/microcontrollers/{name}")]
13    public void Post(string name) {
14      dataModel._name = name; // Save the naem
15    }
17    [Route("api/microcontrollers/{id}")]
18    public void Delete(int id) {
19      dataModel.Delete(x => x._id == id); // Sample function to delete the data.
20    }
22    /*
23    * You can add other functions named with the HTTP verb
24    * such as:
25    * 1. PUT
26    * 2. OPTIONS
27    * etc.
28    */
29  }

This is a complete Web API for your controllers. Although this doesn't support many of the features of the API, it should help you understand the advantages of mapping the Web API. Notice how simple this program is? The rest of the job is done by the handling method where you define how your routines are defined for the URL mapping.

Writing Other HTTP URL Helpers

Since the program is very simple, I willshow you how to add more URLs to be handled in this specific controller of your application. Note that we have routed our application to the HTTP requests using the Route[("path")] attribute over the actions of the controllers. We can use these on other actions, to define different routes in the same controller.

Take a look at the above code and see the HTTP GET action handler. What if we wanted to handle another GET request?

For that, we can change the URL that we want to map to and still handle that request under this controller. Like this:

2public string Get() {
3  return "Hello world, from another URL.";

Now if we change the request to the URL localhost:12345/api/microcontrollers/anotherurl, we will be mapped to an action and the result will be generated from this action. This is really helpful and makes it easy to handle multiple URLs and actions under the same controller, without having to create a separate module for each of the URLs that are going to be mapped or raise an error.

Connecting to the Web Service

As we know, our service is a basic HTTP-based service that can be consumed easily using any HTTP client. Most frameworks provide support for HTTP communication and every operating system has APIs that allow HTTP-based communication over the network.

Basically, you won't have to worry about anything before you start working. HTTP clients are provided in C#, Java, C++, Python, and almost every other programming language, in order to facilitate in-application network communication. I will walk you though the .NET framework's HTTP clients that allow HTTP communication with your services.


The .NET framework usually uses the HttpClient object (contrast this with WebClient). This provides your applications access to the network communication and allows you to send requests with the HTTP verbs such as GET, POST, and so on. You can also publish the content to the server after serializing the data for the publishing processes.

Like other IDisposable objects, HttpClient also allows you to leave the rest of the memory cleanup and dispose of the resources to the .NET framework. This way, you will be able to focus on the network programming and not on the memory cleanup, most of the time.

Next, let's see how to connect to the services using HttpClient object in .NET applications.

Note that you can use HttpClient in any project or application, if you can target the System.Net.Http namespace in your application.

The main function of the program would look something like this:

1// // Namespace import
2using System.Net.Http;
4// Deep inside the function
5using (var client = new HttpClient()) {
6  // Use the API here.

This is the template that you should use for consuming the application service. For instance, the basic program for getting a "Hello world" message from the API would look like this:

1using (var client = new HttpClient())
3  // It is recommended to add a base address, instead of pushing this to the HTTP request functions.
4  client.BaseAddress = new Uri("http://localhost:12345/");
6  // Get the response from the API
7  var response = await client.GetAsync("api/microcontrollers/");
9  // Check if the request succeeded.
10  if (response.IsSuccessStatusCode)
11  {
12    // Get the message.
13    var msg = await response.Content.ReadAsStringAsync();
14    Console.WriteLine(msg); // Hello, world!
15  }

This way, you can access the API remotely. The other ASP.NET basics are similar. For example, HttpClient allows you to use other functions to perform other HTTP requests, such as POST, where you get to publish some content to the servers. Note that publishing requires a bit of a complex method where you also have to wrap and pass the data in the form of a bytes array to the server. This data is then loaded and read on the server side.

In case of micro-controllers, that doesn't make much sense because you are unlikely to stream media (and thus use a bytes array). As such, you can surely check out one of the many articles about network programming in the .NET framework on micro-controllers.


Thank you for reading. I hope you now understand the many advantages of ASP.NET when compared to the traditional WCF framework. Furthermore, I hope that the similarities among the platforms indicate to you that the notion of IoT is not actually as "new" as it's made out to be!