A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/unosquare/embedio/tree/v2.X below:

GitHub - unosquare/embedio at v2.X

⭐ Please star this project if you find it useful!

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

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

Note - We encourage to upgrade to the newest EmbedIO version. Branch version 1.X will no longer be maintained, and issues will be tested against 2.X and resolved just there.

You can start using EmbedIO by just downloading the nuget.

PM> Install-Package EmbedIO
> dotnet add package EmbedIO
IHttpContext Extension Methods

By adding the namespace Unosquare.Labs.EmbedIO to your class, you can use some helpful extension methods for IHttpContext, IHttpResponse and IHttpRequest. These methods can be used in any Web module (like Fallback Module) or inside a WebAPI Controller method.

Below, some common scenarios using a WebAPI Controller method as body function:

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

For reading a dictionary from a HTTP Request body you can use RequestFormDataDictionaryAsync. This method works directly from IHttpContext and returns the key-value pairs sent by using the Contet-Type 'application/x-www-form-urlencoded'.

    [WebApiHandler(HttpVerbs.Post, "/api/data")]
    public async Task<bool> PostData() 
    {
        var data = await HttpContext.RequestFormDataDictionaryAsync();
	// Perform an operation with the data
	await SaveData(data);
	
	return true;
    }
Reading from a POST body as a JSON payload (application/json)

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

    [WebApiHandler(HttpVerbs.Post, "/api/data")]
    public async Task<bool> PostJsonData() 
    {
        var data = HttpContext.ParseJson<MyData>();
	// Perform an operation with the data
	await SaveData(data);
	
	return true;
    }
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.

There is another solution but it requires this Microsoft Nuget.

For writing a binary stream directly to the Response Output Stream you can use BinaryResponseAsync. This method has an overload to use IHttpContext and you need to set the Content-Type beforehand.

    [WebApiHandler(HttpVerbs.Get, "/api/binary")]
    public async Task<bool> GetBinary() 
    {
        var stream = new MemoryStream();
	
	// Call a fictional external source
	await GetExternalStream(stream);
	
	return await HttpContext.BinaryResponseAsync(stream);
    }
Serving Files from Assembly

You can use files from Assembly Resources directly with EmbedIO. They will be served as local files. This is a good practice when you want to provide a web server solution in a single file.

First, you need to add the ResourceFilesModule module to your IWebServer. The ResourceFilesModule constructor takes two arguments, the Assembly reference where the Resources are located and the path to the Resources (Usually this path is the Assembly name plus the word "Resources").

using (var server = new WebServer(url)) 
{
	server.RegisterModule(new ResourceFilesModule(typeof(MyProgram).Assembly,
                        "Unosquare.MyProgram.Resources"));
	
	// Continue with the server set up and initialization
}

And that's all. The module will read the files in the Assembly using the second argument as the base path. For example, if you have a folder containing an image, the resource path can be Unosquare.MyProgram.Resources.MyFolder.Image.jpg and the relative URL is /MyFolder/Image.jpg.

Both HTTP listeners (Microsoft and Unosquare) can open a web server using SSL. This support is for Windows only (for now) and you need to manually register your certificate or use the WebServerOptions class to initialize a new WebServer instance. This section will provide some examples of how to use SSL but first a brief explanation of how SSL works on Windows.

For Windows Vista or better, Microsoft provides Network Shell (netsh). This command line tool allows to map an IP-port to a certificate, so incoming HTTP request can upgrade the connection to a secure stream using the provided certificate. EmbedIO can read or register certificates to a default store (My/LocalMachine) and use them against a netsh sslcert for binding the first https prefix registered.

For Windows XP and Mono, you can use manually the httpcfg for registering the binding.

Using a PFX file and AutoRegister option

The more practical case to use EmbedIO with SSL is the AutoRegister option. You need to create a WebServerOptions instance with the path to a PFX file and the AutoRegister flag on. This options will try to get or register the certificate to the default certificate store. Then it will use the certificate thumbprint to register with netsh the FIRST https prefix registered on the options.

If you already have a certificate on the default certificate store and the binding is also registered in netsh, you can use Autoload flag and optionally provide a certificate thumbprint. If the certificate thumbprint is not provided, EmbedIO will read the data from netsh. After getting successfully the certificate from the store, the raw data is passed to the WebServer.

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

namespace Unosquare
{
    using System;
    using Unosquare.Labs.EmbedIO;
    using Unosquare.Labs.EmbedIO.Modules;

    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 = new WebServer(url))
            {
                // 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 Redis
                server.WithLocalSession();

                // Here we setup serving of static files
                server.RegisterModule(new StaticFilesModule("c:/web"));
                // The static files module will cache small files in ram until it detects they have been modified.
                server.Module<StaticFilesModule>().UseRamCache = true;

                // Once we've registered our modules and configured them, we call the RunAsync() method.
                server.RunAsync();

                // Fire up the browser to show the content if we are debugging!
#if DEBUG
                var browser = new System.Diagnostics.Process()
                {
                    StartInfo = new System.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 our web server using
                // something like a BackgroundWorker or a ManualResetEvent.
                Console.ReadKey(true);
            }
        }
    }
}

The WebApi module supports two routing strategies: Wildcard and Regex. By default, the WebApi module will use the Regex Routing Strategy trying to match and resolve the values from a route template, in a similar fashion to Microsoft's Web API.

Note - Wilcard routing will be dropped in the next major version of EmbedIO. We advise to use Regex only.

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:

var server =  new WebServer("http://localhost:9696/", RoutingStrategy.Regex);

server.RegisterModule(new WebApiModule());
server.Module<WebApiModule>().RegisterController<PeopleController>();

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

// A controller is a class where the WebApi module will find available
// endpoints. The class must extend WebApiController.
public class PeopleController : WebApiController
{
    // You need to add a default constructor where the first argument
    // is an IHttpContext
    public PeopleController(IHttpContext context)
        : base(context)
    {
    }

    // You need to include the WebApiHandler attribute to each method
    // where you want to export an endpoint. The method should return
    // bool or Task<bool>.
    [WebApiHandler(HttpVerbs.Get, "/api/people/{id}")]
    public async Task<bool> GetPersonById(int id)
    {
        try
        {
            // This is fake call to a Repository
            var person = await PeopleRepository.GetById(id);
            return await Ok(person);
        }
        catch (Exception ex)
        {
            return await InternalServerError(ex);
        }
    }
    
    // You can override the default headers and add custom headers to each API Response.
    public override void SetDefaultHeaders() => HttpContext.NoCache();
}

The SetDefaultHeaders method will add a no-cache policy to all Web API responses. If you plan to handle a differente policy or even custom headers to each different Web API method we recommend you override this method as you need.

The previous default strategy (Wildcard) matches routes using the asterisk * character in the route. For example:

During server setup:

var server =  new WebServer("http://localhost:9696/", RoutingStrategy.Regex);

server.RegisterModule(new WebApiModule());
server.Module<WebApiModule>().RegisterController<PeopleController>();
public class PeopleController : WebApiController
{
    public PeopleController(IHttpContext context)
    : base(context)
    {
    }

    [WebApiHandler(HttpVerbs.Get, "/api/people/*")]
    public async Task<bool> GetPeopleOrPersonById()
    {
        var lastSegment = Request.Url.Segments.Last();

        // If the last segment is a backslash, return all
        // the collection. This endpoint call a fake Repository.
        if (lastSegment.EndsWith("/"))
            return await Ok(await PeopleRepository.GetAll());
                
        if (int.TryParse(lastSegment, out var id))
        {
            return await Ok(await PeopleRepository.GetById(id));
        }

        throw new KeyNotFoundException("Key Not Found: " + lastSegment);
    }
}

During server setup:

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

And our web sockets server class looks like:

/// <summary>
/// Defines a very simple chat server
/// </summary>
public class WebSocketsChatServer : WebSocketsServer
{
    public WebSocketsChatServer()
        : base(true)
    {
        // placeholder
    }

    public override string ServerName => "Chat Server";

    protected override void OnMessageReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult)
    {
        foreach (var ws in WebSockets)
        {
            if (ws != context)
                Send(ws, rxBuffer.ToText());
        }
    }

    protected override void OnClientConnected(
        IWebSocketContext context,
        System.Net.IPEndPoint localEndPoint,
        System.Net.IPEndPoint remoteEndPoint)
    {
        Send(context, "Welcome to the chat room!");
        
        foreach (var ws in WebSockets)
        {
            if (ws != context)
                Send(ws, "Someone joined the chat room.");
        }
    }

    protected override void OnFrameReceived(IWebSocketContext context, byte[] rxBuffer, IWebSocketReceiveResult rxResult)
    {
        // placeholder
    }

    protected override void OnClientDisconnected(IWebSocketContext context)
    {
        Broadcast("Someone left the chat room.");
    }
}
Related Projects and Nugets Name Author Description Butterfly.EmbedIO Fireshark Studios, LLC Implementation of Butterfly.Core.Channel and Butterfly.Core.WebApi using the EmbedIO server embedio-cli Unosquare A dotnet global tool that enables start any web folder or EmbedIO assembly (WebAPI or WebSocket) from command line. EmbedIO.BearerToken Unosquare Allow to authenticate with a Bearer Token. It uses a Token endpoint (at /token path) and with a defined validation delegate create a JsonWebToken. The module can check all incoming requests or a paths EmbedIO.LiteLibWebApi Unosquare Allow to expose a sqlite database as REST api using EmbedIO WebApi and LiteLib libraries EmbedIO.OWIN Unosquare EmbedIO can use the OWIN platform in two different approach: You can use EmbedIO as OWIN server and use all OWIN framework with EmbedIO modules. Microsoft.AspNetCore.Server.EmbedIO Dju EmbedIO web server support for ASP.NET Core, as a drop-in replacement for Kestrel SambaFetcher nddipiazza A .NET tool to connect a web server with Samba

To YourKit for supports open source projects with its full-featured .NET Profiler, an amazing tool to profile CPU and Memory!


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4