Pluralsight Logo
Author avatar

Afzaal Ahmad Zeeshan

Author badge Author

Building and Connecting ASP.NET Web API for IoT

Afzaal Ahmad Zeeshan

Author BadgeAuthor
  • Sep 19, 2018
  • 7 Min read
  • 45,977 Views
  • Sep 19, 2018
  • 7 Min read
  • 45,977 Views
ASP.NET
API
IOT

Introduction

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Add the namespace imports
namespace Sample {

  // Add the route attribute, this would be accessible at: localhost:12345/api/microcontrollers/
  [Route("api/microcontrollers")]
  public class MicroControllers : ApiController { // Note the inheritance
    // Adding the HTTP helpers
    public string Get() {
      return "Hello, world!";
    }

    [Route("api/microcontrollers/{name}")]
    public void Post(string name) {
      dataModel._name = name; // Save the naem
    }

    [Route("api/microcontrollers/{id}")]
    public void Delete(int id) {
      dataModel.Delete(x => x._id == id); // Sample function to delete the data.
    }

    /*
    * You can add other functions named with the HTTP verb
    * such as:
    * 1. PUT
    * 2. OPTIONS
    * etc.
    */
  }
}
csharp

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:

1
2
3
4
[Route("api/microcontrollers/anotherurl")]
public string Get() {
  return "Hello world, from another URL.";
}
csharp

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.

HttpClient

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
2
3
4
5
6
7
// // Namespace import
using System.Net.Http;

// Deep inside the function
using (var client = new HttpClient()) {
  // Use the API here.
}
csharp

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using (var client = new HttpClient())
{
  // It is recommended to add a base address, instead of pushing this to the HTTP request functions.
  client.BaseAddress = new Uri("http://localhost:12345/");

  // Get the response from the API
  var response = await client.GetAsync("api/microcontrollers/");

  // Check if the request succeeded.
  if (response.IsSuccessStatusCode)
  {
    // Get the message.
    var msg = await response.Content.ReadAsStringAsync();
    Console.WriteLine(msg); // Hello, world!
  }
}
csharp

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.

Conclusion

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!

0