This guide is for you, if you are:
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.
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 {
3
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 }
11
12 [Route("api/microcontrollers/{name}")]
13 public void Post(string name) {
14 dataModel._name = name; // Save the naem
15 }
16
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 }
21
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 }
30}
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.
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[Route("api/microcontrollers/anotherurl")]
2public string Get() {
3 return "Hello world, from another URL.";
4}
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.
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 theSystem.Net.Http
namespace in your application.
The main function of the program would look something like this:
1// // Namespace import
2using System.Net.Http;
3
4// Deep inside the function
5using (var client = new HttpClient()) {
6 // Use the API here.
7}
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())
2{
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/");
5
6 // Get the response from the API
7 var response = await client.GetAsync("api/microcontrollers/");
8
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 }
16}
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!