EmbedIO v3

By Geo Perez - 04 Sep 2019
EmbedIO web net.core .net http

A couple of weeks ago, we proudly release a new major version of EmbedIO. The lightweight web server for your .NET projects.

This major version was a monumental effort of one new contributor from Italy, Riccardo De Agostini @rdeago. Thanks again!

EmbedIO v3 includes most of the features that you might already know of the previous version. But now we have a better framework to construct Web Modules and, an even better, way to handle the incoming HTTP traffic. Still keeping all tight in a single assembly with minimal dependencies (SWAN Lite).

On this initial post, let’s focus on the new Web API. We can start from scratch to understand how Web API works and the benefits of this WebModule.

We need to instantiate a new WebServer class and attach a Web API module using the extension method WithWebApi like the following example:

var server = new WebServer("http://localhost:1234")
                .WithWebApi("/api", m => m
                    .WithController<SampleController>());

The SampleController is a WebApiController that we need to create. So let’s do it!

public class SampleController : WebApiController 
{
	[Route(HttpVerbs.Get, "/version")]
	public object GetVersion() => return new { Version = "1.0.0" };
}

The previous code will create a simple endpoint at “/api/version” returning a JSON response with a property Version and value 1.0.0. Simple, right?

Registering a WebAPI module allows setting the initial path segment where the endpoints will respond. Then the attribute Route will set a verb and a final URL segment to bind with a class method. This class method can return an object or Task of an object, or even void. This last one will response an HTTP Status 200 without a body.

If you are trying to get information from the client, you can choose HTTP POST to receive a payload. Check the following snippet, where the API will respond with the same object:

    [Route(HttpVerbs.Post, "/echo")]
    public async Task<object> Echo() => return await HttpContext.GetRequestDataAsync<object>();

Let me introduce the HttpContext property. The class WebApiController contains some properties to access the HTTP elements of the Request/Response process. HttpContext contains both, and it has some shortcuts to common actions in extension methods. One of those is GetRequestDataAsync, this extension method will read the entire body of the HTTP Request and deserialize it in the generic type provided.

You can continue experimenting with the extension methods. In the next blog post, I will explain how to read from other content types and how to handle exceptions.

Comments