Language: EN

embedio-una-libreria-en-c-para-crear-un-servidor-http-para-net

EmbedIO, C# library to create an HTTP server in .NET

EmbedIO is a small multiplatform server for .Net Framework and .Net Core that we can add to projects that receive HTTP requests without the need for a complete web server.

EmbedIO is written entirely in C#, and its development is focused on achieving high efficiency with low memory consumption. All operations are available in asynchronous version.

It is distributed under the MIT license, and all the code and documentation is available at https://github.com/unosquare/embedio. Embed IO is compatible with .NET for Windows, Mono, and Xamarin.

Install EmbedIO

The EmbedIO library is distributed as a Nutget package, so adding it to our project is as simple as:

Install-Package EmbedIO

Example of EmbedIO usage

Let’s make a small example to illustrate the use of EmbedIO. For this, we create a simple console application, and replace the code with the following.


internal static class Program
{
  [STAThread]
  private static void Main()
  {
    var url = "http://localhost:9696/";

    using (WebServer server = CreateWebServer(url))
    {
      server.RunAsync();
    }

    Console.ReadKey(true);
  }

  // Create and configure our web server.
  private static WebServer CreateWebServer(string url)
  {
    WebServer server = new WebServer(o => o
        .WithUrlPrefix(url)
        .WithMode(HttpListenerMode.EmbedIO))
      .WithLocalSessionManager()
      .WithAction("/test", HttpVerbs.Any, ctx =>
        {
          Console.WriteLine("Request received");
          return ctx.SendDataAsync(new { mensaje = "Hello world"});
        }
      );

    // Listen for state changes.
    server.StateChanged += (s, e) => $"WebServer New State - {e.NewState}".Info();

    return server;
  }
}

That’s how simple it is to create an Endpoint for the Url http://localhost:9696/test, which returns a Json file with “Hello world”, and shows on the console that it has received a request.

In a real example, of course, the server would perform the necessary actions, and the data returned would, for example, be loaded from a data source.

Of course, this is just a small example of what EmbedIO can do. We can also serve static pages, manage user sessions, use Websockets. It also incorporates support for Cors.

It also has an interesting module to configure a complete Rest API easily. We can literally generate a Rest API in minutes.

Finally, it is extensible. Its modular design allows us to add our own modules, for example, to configure middleware.

In summary, a very interesting library that, while it is true that it does not fit into all projects, can be useful in those apps that require simple and efficient handling of HTTP requests.