SkillAgentSearch skills...

Embedio

A tiny, cross-platform, module based web server for .NET

Install / Use

/learn @unosquare/Embedio

README

Analytics Build status Buils status NuGet version NuGet BuiltWithDotnet Slack

EmbedIO

:star: Please star this project if you find it useful!

This README is for EmbedIO v3.x. Click here if you are still using EmbedIO v2.x.

Overview

A tiny, cross-platform, module based, MIT-licensed web server for .NET Framework and .NET Core.

  • Written entirely in C#, using our helpful library SWAN
  • Network operations use the async/await pattern: Responses are handled asynchronously
  • Multiple implementations support: EmbedIO can use Microsoft HttpListener or internal Http Listener based on Mono/websocket-sharp projects
  • Cross-platform: tested on multiple OS and runtimes. From Windows .NET Framework to Linux MONO.
  • Extensible: Write your own modules -- For example, video streaming, UPnP, etc. Check out EmbedIO Extras for additional modules
  • Small memory footprint
  • Create REST APIs quickly with the out-of-the-box Web API module
  • Serve static or embedded files with 1 line of code (also out-of-the-box)
  • Handle sessions with the built-in LocalSessionWebModule
  • WebSockets support
  • CORS support. Origin, Header and Method validation with OPTIONS preflight
  • HTTP 206 Partial Content support
  • Support Xamarin Forms
  • And many more options in the same package

EmbedIO 3.0 - What's new

The major version 3.0 includes a lot of changes in how the webserver process the incoming request and the pipeline of the Web Modules. You can check a complete list of changes and a upgrade guide for v2 users here.

Some usage scenarios:

  • Write a cross-platform GUI entirely using React/AngularJS/Vue.js or any Javascript framework
  • Write a game using Babylon.js and make EmbedIO your serve your code and assets
  • Create GUIs for Windows services or Linux daemons
  • Works well with LiteLib - add SQLite support in minutes!
  • Write client applications with real-time communication between them using WebSockets
  • Write internal web server for Xamarin Forms applications

Installation:

You can start using EmbedIO by just downloading the nuget.

Package Manager

PM> Install-Package EmbedIO

.NET CLI

> dotnet add package EmbedIO

Usage

Working with EmbedIO is pretty simple, check the follow sections to start coding right away. You can find more useful recipes and implementation details in the Cookbook.

WebServer Setup

Please note the comments are the important part here. More info is available in the samples.

namespace Unosquare
{
    using System;
    using EmbedIO;
    using EmbedIO.WebApi;

    class Program
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        static void Main(string[] args)
        {
            var url = "http://localhost:9696/";
            if (args.Length > 0)
                url = args[0];

            // Our web server is disposable.
            using (var server = CreateWebServer(url))
            {
                // Once we've registered our modules and configured them, we call the RunAsync() method.
                server.RunAsync();

                var browser = new System.Diagnostics.Process()
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true }
                };
                browser.Start();
                // Wait for any key to be pressed before disposing of our web server.
                // In a service, we'd manage the lifecycle of our web server using
                // something like a BackgroundWorker or a ManualResetEvent.
                Console.ReadKey(true);
            }
        }
	
	// Create and configure our web server.
        private static WebServer CreateWebServer(string url)
        {
            var server = new WebServer(o => o
                    .WithUrlPrefix(url)
                    .WithMode(HttpListenerMode.EmbedIO))
		 // First, we will configure our web server by adding Modules.
                .WithLocalSessionManager()
                .WithWebApi("/api", m => m
                    .WithController<PeopleController>())
                .WithModule(new WebSocketChatModule("/chat"))
                .WithModule(new WebSocketTerminalModule("/terminal"))
                .WithStaticFolder("/", HtmlRootPath, true, m => m
                    .WithContentCaching(UseFileCache)) // Add static files after other modules to avoid conflicts
                .WithModule(new ActionModule("/", HttpVerbs.Any, ctx => ctx.SendDataAsync(new { Message = "Error" })));

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

            return server;
        }
    }
}

Reading from a POST body as a dictionary (application/x-www-form-urlencoded)

For reading a dictionary from an HTTP Request body inside a WebAPI method you can add an argument to your method with the attribute FormData.

    [Route(HttpVerbs.Post, "/data")]
    public async Task PostData([FormData] NameValueCollection data) 
    {
        // Perform an operation with the data
        await SaveData(data);
    }

Reading from a POST body as a JSON payload (application/json)

For reading a JSON payload and deserialize it to an object from an HTTP Request body you can use GetRequestDataAsync<T>. This method works directly from IHttpContext and returns an object of the type specified in the generic type.

    [Route(HttpVerbs.Post, "/data")]
    public async Task PostJsonData() 
    {
        var data = HttpContext.GetRequestDataAsync<MyData>();
	
        // Perform an operation with the data
        await SaveData(data);
    }

Reading from a POST body as a FormData (multipart/form-data)

EmbedIO doesn't provide the functionality to read from a Multipart FormData stream. But you can check the HttpMultipartParser Nuget and connect the Request input directly to the HttpMultipartParser, very helpful and small library.

A sample code using the previous library:

    [Route(HttpVerbs.Post, "/upload")]
    public async Task UploadFile()
    {
        var parser = await MultipartFormDataParser.ParseAsync(Request.InputStream);
        // Now you can access parser.Files
    }

There is another solution but it requires this Microsoft Nuget.

Writing a binary stream

You can open the Response Output Stream with the extension OpenResponseStream.

    [Route(HttpVerbs.Get, "/binary")]
    public async Task GetBinary() 
    {
	// Call a fictional external source
	using (var stream = HttpContext.OpenResponseStream())
                await stream.WriteAsync(dataBuffer, 0, 0);
    }

WebSockets Example

Working with WebSocket is pretty simple, you just need to implement the abstract class WebSocketModule and register the module to your Web server as follow:

server..WithModule(new WebSocketChatModule("/chat"));

And our web sockets server class looks like:

namespace Unosquare
{
    using EmbedIO.WebSockets;

    /// <summary>
    /// Defines a very simple chat server.
    /// </summary>
    public class WebSocketsChatServer : WebSocketModule
    {
        public WebSocketsChatServer(string urlPath)
            : base(urlPath, true)
        {
            // placeholder
        }

        /// <inheritdoc />
        protected override Task OnMessageReceivedAsync(
            
View on GitHub
GitHub Stars1.6k
CategoryDevelopment
Updated1d ago
Forks191

Languages

C#

Security Score

85/100

Audited on Apr 2, 2026

No findings