Skip to content

Repository files navigation

AnalyticsBuild statusBuild StatusNuGet versionCoverage Status

EmbedIO

⭐Please star this project if you find it useful!

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

  • Written entirely in C#
  • Network operations use the async/await pattern: Responses are handled asynchronously
  • Cross-platform: tested in Mono 3.10.x on Windows and on a custom Yocto image for the Raspberry Pi
  • 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 files with 1 line of code (also out-of-the-box)
  • Handle sessions with the built-in LocalSessionWebModule
  • Web Sockets support (Not available on Mono 3.x though)
  • CORS support. Origin, Header and Method validation with OPTIONS preflight
  • Supports HTTP 206 Partial Content
  • OWIN Middleware support via Owin Middleware Module.

For detailed usage and REST API implementation, download the code and take a look at the Samples project

Some usage scenarios:

  • Write a cross-platform GUI entirely in CSS/HTML/JS
  • Write a game using Babylon.js and make EmbedIO your serve your code and assets
  • Create GUIs for Windows services or Linux daemons
  • Write client applications with real-time communication between them

NuGet Installation:

PM> Install-Package EmbedIO

Basic Example:

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

namespaceCompany.Project{usingSystem;usingUnosquare.Labs.EmbedIO;usingUnosquare.Labs.EmbedIO.Log;usingUnosquare.Labs.EmbedIO.Modules;classProgram{/// <summary>/// Defines the entry point of the application./// </summary>/// <param name="args">The arguments.</param>staticvoidMain(string[]args){varurl="http://localhost:9696/";if(args.Length>0)url=args[0];// Our web server is disposable. Note that if you don't want to use logging,// there are alternate constructors that allow you to skip specifying an ILog object.using(varserver=newWebServer(url,newSimpleConsoleLog())){// First, we will configure our web server by adding Modules.// Please note that order DOES matter.// ================================================================================================// If we want to enable sessions, we simply register the LocalSessionModule// Beware that this is an in-memory session storage mechanism so, avoid storing very large objects.// You can use the server.GetSession() method to get the SessionInfo object and manupulate it.// You could potentially implement a distributed session module using something like Redisserver.RegisterModule(newLocalSessionModule());// Here we setup serving of static filesserver.RegisterModule(newStaticFilesModule("c:/web"));// The static files module will cache small files in ram until it detects they have been modified.server.Module<StaticFilesModule>().UseRamCache=true;server.Module<StaticFilesModule>().DefaultExtension=".html";// We don't need to add the line below. The default document is always index.html.//server.Module<Modules.StaticFilesWebModule>().DefaultDocument = "index.html";// Once we've registered our modules and configured them, we call the RunAsync() method.// This is a non-blocking method (it return immediately) so in this case we avoid// disposing of the object until a key is pressed.//server.Run();server.RunAsync();// Fire up the browser to show the content if we are debugging!
#if DEBUGvarbrowser=newSystem.Diagnostics.Process(){StartInfo=newSystem.Diagnostics.ProcessStartInfo(url){UseShellExecute=true}};browser.Start();
#endif
// Wait for any key to be pressed before disposing of our web server.// In a service we'd manage the lifecycle of of our web server using// something like a BackgroundWorker or a ManualResetEvent.Console.ReadKey(true);}}}}

Fluent Example:

Many extension methods are available. This allows you to create a web server instance in a fluent style by dotting in configuration options.

namespaceCompany.Project{usingSystem;usingUnosquare.Labs.EmbedIO;internalclassProgram{/// <summary>/// Defines the entry point of the application./// </summary>/// <param name="args">The arguments.</param>privatestaticvoidMain(string[]args){varurl="http://localhost:9696/";if(args.Length>0)url=args[0];// Create Webserver with console logger and attach LocalSession and Static// files module and CORS enabledvarserver=WebServer.CreateWithConsole(url).EnableCors().WithLocalSession().WithStaticFolderAt("c:/web");varcts=newCancellationTokenSource();vartask=server.RunAsync(cts.Token);// Fire up the browser to show the content if we are debugging!
#if DEBUGvarbrowser=newSystem.Diagnostics.Process(){StartInfo=newSystem.Diagnostics.ProcessStartInfo(url){UseShellExecute=true}};browser.Start();
#endif
// Wait for any key to be pressed before disposing of our web server.// In a service we'd manage the lifecycle of of our web server using// something like a BackgroundWorker or a ManualResetEvent.Console.ReadKey(true);cts.Cancel();try{task.Wait();}catch(AggregateException){// We'd also actually verify the exception cause was that the task// was cancelled.server.Dispose();}}}}

REST API Example:

The WebApi module supports two routing strategies: Wildcard and Regex. By default, and in order to maintain backwards compatibility, the WebApi module will use the Wildcard Routing Strategy and match routes using the asterisk * character in the route. For example:

  • The route /api/people/* will match any request with a URL starting with the two first URL segments api and people and ending with anything. The route /api/people/hello will be matched.
  • You can also use wildcards in the middle of the route. The route /api/people/*/details will match requests starting with the two first URL segments api and people, and ending with a details segment. The route /api/people/hello/details will be matched.

Note that most REST services can be designed with this simpler Wildcard routing startegy. However, the Regex matching strategy is the current recommended approach as we might be deprecating the Wildcard strategy altogether

On the other hand, the Regex Routing Strategy will try to match and resolve the values from a route template, in a similar fashion to Microsoft's Web API 2. A method with the following route /api/people/{id} is going to match any request URL with three segments: the first two api and people and the last one is going to be parsed or converted to the type in the id argument of the handling method signature. Please read on if this was confusing as it is much simpler than it sounds. Additionally, you can put multiple values to match, for example /api/people/{mainSkill}/{age}, and receive the parsed values from the URL straight into the arguments of your handler method.

During server setup:

// The routing strategy is Wildcard by default, but you can change it to Regex as follows:varserver=newWebServer("http://localhost:9696/",newNullLog(),RoutingStrategy.Regex);server.RegisterModule(newWebApiModule());server.Module<WebApiModule>().RegisterController<PeopleController>();

And our controller class (using Regex Strategy) looks like:

publicclassPeopleController:WebApiController{[WebApiHandler(HttpVerbs.Get,"/api/people/{id}")]publicboolGetPeople(WebServerserver,HttpListenerContextcontext,intid){try{if(People.Any(p =>p.Key==id)){returncontext.JsonResponse(People.FirstOrDefault(p =>p.Key==id));}}catch(Exceptionex){returnHandleError(context,ex,(int)HttpStatusCode.InternalServerError);}}protectedboolHandleError(HttpListenerContextcontext,Exceptionex,intstatusCode=500){varerrorResponse=new{Title="Unexpected Error",ErrorCode=ex.GetType().Name,Description=ex.ExceptionMessage(),};context.Response.StatusCode=statusCode;returncontext.JsonResponse(errorResponse);}}

Or if you want to use the Wildcard strategy (which is the default):

publicclassPeopleController:WebApiController{[WebApiHandler(HttpVerbs.Get,"/api/people/*")]publicboolGetPeople(WebServerserver,HttpListenerContextcontext){try{varlastSegment=context.Request.Url.Segments.Last();if(lastSegment.EndsWith("/"))returncontext.JsonResponse(People);intkey=0;if(int.TryParse(lastSegment,outkey)&&People.Any(p =>p.Key==key)){returncontext.JsonResponse(People.FirstOrDefault(p =>p.Key==key));}thrownewKeyNotFoundException("Key Not Found: "+lastSegment);}catch(Exceptionex){returnHandleError(context,ex,(int)HttpStatusCode.InternalServerError);}}protectedboolHandleError(HttpListenerContextcontext,Exceptionex,intstatusCode=500){varerrorResponse=new{Title="Unexpected Error",ErrorCode=ex.GetType().Name,Description=ex.ExceptionMessage(),};context.Response.StatusCode=statusCode;returncontext.JsonResponse(errorResponse);}}

Web Sockets Example:

During server setup:

server.RegisterModule(newWebSocketsModule());server.Module<WebSocketsModule>().RegisterWebSocketsServer<WebSocketsChatServer>("/chat");

And our web sockets server class looks like:

/// <summary>/// Defines a very simple chat server/// </summary>publicclassWebSocketsChatServer:WebSocketsServer{publicWebSocketsChatServer():base(true,0){// placeholder}/// <summary>/// Called when this WebSockets Server receives a full message (EndOfMessage) form a WebSockets client./// </summary>/// <param name="context">The context.</param>/// <param name="rxBuffer">The rx buffer.</param>/// <param name="rxResult">The rx result.</param>protectedoverridevoidOnMessageReceived(WebSocketContextcontext,byte[]rxBuffer,WebSocketReceiveResultrxResult){varsession=this.WebServer.GetSession(context);foreach(varwsinthis.WebSockets){if(ws!=context)this.Send(ws,Encoding.UTF8.GetString(rxBuffer));}}/// <summary>/// Gets the name of the server./// </summary>/// <value>/// The name of the server./// </value>publicoverridestringServerName{get{return"Chat Server";}}/// <summary>/// Called when this WebSockets Server accepts a new WebSockets client./// </summary>/// <param name="context">The context.</param>protectedoverridevoidOnClientConnected(WebSocketContextcontext){this.Send(context,"Welcome to the chat room!");foreach(varwsinthis.WebSockets){if(ws!=context)this.Send(ws,"Someone joined the chat room.");}}/// <summary>/// Called when this WebSockets Server receives a message frame regardless if the frame represents the EndOfMessage./// </summary>/// <param name="context">The context.</param>/// <param name="rxBuffer">The rx buffer.</param>/// <param name="rxResult">The rx result.</param>protectedoverridevoidOnFrameReceived(WebSocketContextcontext,byte[]rxBuffer,WebSocketReceiveResultrxResult){return;}/// <summary>/// Called when the server has removed a WebSockets connected client for any reason./// </summary>/// <param name="context">The context.</param>protectedoverridevoidOnClientDisconnected(WebSocketContextcontext){this.Broadcast(string.Format("Someone left the chat room."));}}

About

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

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages