All Projects → nanoframework → nanoFramework.WebServer

nanoframework / nanoFramework.WebServer

Licence: MIT License
📦 Web server for nanoFramework packed with features: REST api using attributes, multithread requests, parameters in query URL, static files serving.

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to nanoFramework.WebServer

SnorkTracker
GPS IoT tracker board for scanning gps and environment information and sending this to a MQTT server via GPRS.
Stars: ✭ 38 (+153.33%)
Mutual labels:  webserver, esp32
LMIC-node
LMIC-node | One example to rule them all. LMIC-node is an example LoRaWAN application for a node that can be used with The Things Network. It demonstrates how to send uplink messages, how to receive downlink messages, how to implement a downlink command and it provides useful status information. With LMIC-node it is easy to get a working node qu…
Stars: ✭ 108 (+620%)
Mutual labels:  esp32, stm32
grapevine
Fast, unopinionated, embeddable, minimalist web framework for .NET
Stars: ✭ 72 (+380%)
Mutual labels:  restful-api, restful-webservices
wine
A lightweight and flexible framework to help build elegant web API
Stars: ✭ 39 (+160%)
Mutual labels:  webserver, restful-api
ESPxWebFlMgr
Manage your ESP8266/ESP32 SPIFFS/LittleFS files with a simple web based interface
Stars: ✭ 33 (+120%)
Mutual labels:  webserver, esp32
HttpServerLite
TCP-based simple HTTP and HTTPS server, written in C#.
Stars: ✭ 44 (+193.33%)
Mutual labels:  webserver, restful-api
pikascript
Ultralightweight Python engine that can run with 4KB of RAM and 32KB of Flash (such as STM32G030C8 and STM32F103C8), and is very easy to deploy and expand.
Stars: ✭ 855 (+5600%)
Mutual labels:  esp32, stm32
My Ttgo Watch
Firmware for a ttgo-watch2020-v1 smartwatch based on ESP32 from LilyGo.
Stars: ✭ 192 (+1180%)
Mutual labels:  webserver, esp32
FT800-FT813
Multi-Platform C code Library for EVE graphics controllers from FTDI / Bridgetek (FT810, FT811, FT812, FT813, BT815, BT816, BT817, BT818)
Stars: ✭ 80 (+433.33%)
Mutual labels:  esp32, stm32
REST-Api-with-Slim-PHP
REST API with PHP Slim Framework 3 and MySQL
Stars: ✭ 69 (+360%)
Mutual labels:  restful-api, restful-webservices
CoreLibrary
📦 nanoFramework Base Class Library
Stars: ✭ 32 (+113.33%)
Mutual labels:  stm32, nanoframework
poco restful webservice
A RESTful API using Poco C++ Libraries.
Stars: ✭ 54 (+260%)
Mutual labels:  restful-api, restful-webservices
open-rest-es6-boilerplate
open-rest boilerplate project with es6
Stars: ✭ 24 (+60%)
Mutual labels:  restful-api, restful-webservices
WebServer tng
ESP8266/ESP32 WebServer
Stars: ✭ 65 (+333.33%)
Mutual labels:  webserver, esp32
EthernetWebServer SSL
Simple TLS/SSL Ethernet WebServer, HTTP Client and WebSocket Client library for for AVR, Portenta_H7, Teensy, SAM DUE, SAMD21, SAMD51, STM32F/L/H/G/WB/MP1, nRF52 and RASPBERRY_PI_PICO boards using Ethernet shields W5100, W5200, W5500, ENC28J60 or Teensy 4.1 NativeEthernet/QNEthernet. It now supports Ethernet TLS/SSL Client. The library supports …
Stars: ✭ 40 (+166.67%)
Mutual labels:  webserver, stm32
owlos
DIY Open Source OS for building IoT ecosystems
Stars: ✭ 43 (+186.67%)
Mutual labels:  esp32, restful-api
Microwebsrv
A micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (used on Pycom modules & ESP32)
Stars: ✭ 420 (+2700%)
Mutual labels:  webserver, esp32
Bleeper
Library to manage your firmware configurations written in C++
Stars: ✭ 54 (+260%)
Mutual labels:  webserver, esp32
MySQL MariaDB Generic
This MySQL_MariaDB_Generic library helps you connect your boards directly to a MySQL / MariaDB server, either local or cloud-based, so that you can store / retrieve data to / from the server. Supported boards are ESP8266/ESP32, WT32_ETH01 (ESP32 + LAN8720A), nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, SAM DUE, Mega, RP2040-based boards, P…
Stars: ✭ 35 (+133.33%)
Mutual labels:  esp32, stm32
firmware
设备固件库,适用于IntoRobot系列产品
Stars: ✭ 19 (+26.67%)
Mutual labels:  esp32, stm32

Quality Gate Status Reliability Rating License NuGet #yourfirstpr Discord

nanoFramework logo


Welcome to the .NET nanoFramework WebServer repository

Build status

Component Build Status NuGet Package
nanoFramework.WebServer Build Status NuGet
nanoFramework.WebServer (preview) Build Status NuGet

.NET nanoFramework WebServer

This library was coded by Laurent Ellerbach who generously offered it to the .NET nanoFramework project.

This is a simple nanoFramework WebServer. Features:

  • Handle multi-thread requests
  • Serve static files on any storage
  • Handle parameter in URL
  • Possible to have multiple WebServer running at the same time
  • supports GET/PUT and any other word
  • Supports any type of header
  • Supports content in POST
  • Reflection for easy usage of controllers and notion of routes
  • Helpers to return error code directly facilitating REST API
  • HTTPS support
  • URL decode/encode

Limitations:

  • Does not support any zip in the request or response stream

Usage

You just need to specify a port and a timeout for the queries and add an event handler when a request is incoming. With this first way, you will have an event raised every time you'll receive a request.

using (WebServer server = new WebServer(80, HttpProtocol.Http)
{
    // Add a handler for commands that are received by the server.
    server.CommandReceived += ServerCommandReceived;

    // Start the server.
    server.Start();

    Thread.Sleep(Timeout.Infinite);
}

You can as well pass a controller where you can use decoration for the routes and method supported.

using (WebServer server = new WebServer(80, HttpProtocol.Http, new Type[] { typeof(ControllerPerson), typeof(ControllerTest) }))
{
    // Start the server.
    server.Start();

    Thread.Sleep(Timeout.Infinite);
}

In this case, you're passing 2 classes where you have public methods decorated which will be called every time the route is found.

With the previous example, a very simple and straight forward Test controller will look like that:

public class ControllerTest
{
    [Route("test"), Route("Test2"), Route("tEst42"), Route("TEST")]
    [CaseSensitive]
    [Method("GET")]
    public void RoutePostTest(WebServerEventArgs e)
    {
        string route = $"The route asked is {e.Context.Request.RawUrl.TrimStart('/').Split('/')[0]}";
        e.Context.Response.ContentType = "text/plain";
        WebServer.OutPutStream(e.Context.Response, route);
    }

    [Route("test/any")]
    public void RouteAnyTest(WebServerEventArgs e)
    {
        WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.OK);
    }
}

In this example, the RoutePostTest will be called every time the called url will be test or Test2 or tEst42 or TEST, the url can be with parameters and the method GET. Be aware that Test won't call the function, neither test/.

The RouteAnyTestis called whenever the url is test/any whatever the method is.

There is a more advance example with simple REST API to get a list of Person and add a Person. Check it in the sample.

Important

  • By default the routes are not case sensitive and the attribute must be lowercase
  • If you want to use case sensitive routes like in the previous example, use the attribute CaseSensitive. As in the previous example, you must write the route as you want it to be responded to.

A simple GPIO controller REST API

You will find in simple GPIO controller sample REST API. The controller not case sensitive and is working like this:

Authentication on controllers

Controllers support authentication. 3 types of authentications are currently implemented on controllers only:

  • Basic: the classic user and password following the HTTP standard. Usage:
    • [Authentication("Basic")] will use the default credential of the webserver
    • [Authentication("Basic:myuser mypassword")] will use myuser as a user and my password as a password. Note: the user cannot contains spaces.
  • APiKey in header: add ApiKey in headers with the API key. Usage:
    • [Authentication("ApiKey")] will use the default credential of the webserver
    • [Authentication("ApiKeyc:akey")] will use akey as ApiKey.
  • None: no authentication required. Usage:
    • [Authentication("None")] will use the default credential of the webserver

The Authentication attribute applies to both public Classes an public Methods.

As for the rest of the controller, you can add attributes to define them, override them. The following example gives an idea of what can be done:

[Authentication("Basic")]
class ControllerAuth
{
    [Route("authbasic")]
    public void Basic(WebServerEventArgs e)
    {
        WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.OK);
    }

    [Route("authbasicspecial")]
    [Authentication("Basic:user2 password")]
    public void Special(WebServerEventArgs e)
    {
        WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.OK);
    }

    [Authentication("ApiKey:superKey1234")]
    [Route("authapi")]
    public void Key(WebServerEventArgs e)
    {
        WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.OK);
    }

    [Route("authnone")]
    [Authentication("None")]
    public void None(WebServerEventArgs e)
    {
        WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.OK);
    }

    [Authentication("ApiKey")]
    [Route("authdefaultapi")]
    public void DefaultApi(WebServerEventArgs e)
    {
        WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.OK);
    }
}

And you can pass default credentials to the server:

using (WebServer server = new WebServer(80, HttpProtocol.Http, new Type[] { typeof(ControllerPerson), typeof(ControllerTest), typeof(ControllerAuth) }))
{
    // To test authentication with various scenarios
    server.ApiKey = "ATopSecretAPIKey1234";
    server.Credential = new NetworkCredential("topuser", "topPassword");

    // Start the server.
    server.Start();

    Thread.Sleep(Timeout.Infinite);
}

With the previous example the following happens:

  • All the controller by default, even when nothing is specified will use the controller credentials. In our case, the Basic authentication with the default user (topuser) and password (topPassword) will be used.
    • When calling http://yoururl/authbasic from a browser, you will be prompted for the user and password, use the default one topuser and topPassword to get access
    • When calling http://yoururl/authnone, you won't be prompted because the authentication has been overridden for no authentication
    • When calling http://yoururl/authbasicspecial, the user and password are different from the defautl ones, user2 and password is the right couple here
  • If you would have define in the controller a specific user and password like [Authentication("Basic:myuser mypassword")], then the default one for all the controller would have been myuser and mypassword
  • When calling http://yoururl/authapi, you must pass the header ApiKey (case sensitive) with the value superKey1234 to get authorized, this is overridden the default Basic authentication
  • When calling http://yoururl/authdefaultapi, the default key ATopSecretAPIKey1234 will be used so you have to pass it in the headers of the request

All up, this is an example to show how to use authentication, it's been defined to allow flexibility.

Managing incoming queries thru events

Very basic usage is the following:

private static void ServerCommandReceived(object source, WebServerEventArgs e)
{
    var url = e.Context.Request.RawUrl;
    Debug.WriteLine($"Command received: {url}, Method: {e.Context.Request.HttpMethod}");

    if (url.ToLower() == "/sayhello")
    {
        // This is simple raw text returned
        WebServer.OutPutStream(e.Context.Response, "It's working, url is empty, this is just raw text, /sayhello is just returning a raw text");
    }
    else
    {
        WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.NotFound);
    }
}

You can do more advance scenario like returning a full HTML page:

WebServer.OutPutStream(e.Context.Response, "<html><head>" +
    "<title>Hi from nanoFramework Server</title></head><body>You want me to say hello in a real HTML page!<br/><a href='/useinternal'>Generate an internal text.txt file</a><br />" +
    "<a href='/Text.txt'>Download the Text.txt file</a><br>" +
    "Try this url with parameters: <a href='/param.htm?param1=42&second=24&NAme=Ellerbach'>/param.htm?param1=42&second=24&NAme=Ellerbach</a></body></html>");

And can get parameters from a URL a an example from the previous link on the param.html page:

if (url.ToLower().IndexOf("/param.htm") == 0)
{
    // Test with parameters
    var parameters = WebServer.decryptParam(url);
    string toOutput = "<html><head>" +
        "<title>Hi from nanoFramework Server</title></head><body>Here are the parameters of this URL: <br />";
    foreach (var par in parameters)
    {
        toOutput += $"Parameter name: {par.Name}, Value: {par.Value}<br />";
    }
    toOutput += "</body></html>";
    WebServer.OutPutStream(e.Context.Response, toOutput);
}

And server static files:

var files = storage.GetFiles();
foreach (var file in files)
{
    if (file.Name == url)
    {
        WebServer.SendFileOverHTTP(e.Context.Response, file);
        return;
    }
}

WebServer.OutputHttpCode(e.Context.Response, HttpStatusCode.NotFound);

And also REST API is supported, here is a comprehensive example:

if (url.ToLower().IndexOf("/api/") == 0)
{
    string ret = $"Your request type is: {e.Context.Request.HttpMethod}\r\n";
    ret += $"The request URL is: {e.Context.Request.RawUrl}\r\n";
    var parameters = WebServer.DecodeParam(e.Context.Request.RawUrl);
    if (parameters != null)
    {
        ret += "List of url parameters:\r\n";
        foreach (var param in parameters)
        {
            ret += $"  Parameter name: {param.Name}, value: {param.Value}\r\n";
        }
    }

    if (e.Context.Request.Headers != null)
    {
        ret += $"Number of headers: {e.Context.Request.Headers.Count}\r\n";
    }
    else
    {
        ret += "There is no header in this request\r\n";
    }

    foreach (var head in e.Context.Request.Headers?.AllKeys)
    {
        ret += $"  Header name: {head}, Values:";
        var vals = e.Context.Request.Headers.GetValues(head);
        foreach (var val in vals)
        {
            ret += $"{val} ";
        }

        ret += "\r\n";
    }

    if (e.Context.Request.ContentLength64 > 0)
    {

        ret += $"Size of content: {e.Context.Request.ContentLength64}\r\n";
        byte[] buff = new byte[e.Context.Request.ContentLength64];
        e.Context.Request.InputStream.Read(buff, 0, buff.Length);
        ret += $"Hex string representation:\r\n";
        for (int i = 0; i < buff.Length; i++)
        {
            ret += buff[i].ToString("X") + " ";
        }

    }

    WebServer.OutPutStream(e.Context.Response, ret);
}

This API example is basic but as you get the method, you can choose what to do.

As you get the url, you can check for a specific controller called. And you have the parameters and the content payload!

Example of a result with call:

result

And more! Check the complete example for more about this WebServer!

Using HTTPS

You will need to generate a certificate and keys:

X509Certificate _myWebServerCertificate509 = new X509Certificate2(_myWebServerCrt, _myWebServerPrivateKey, "1234");

// X509 RSA key PEM format 2048 bytes
        // generate with openssl:
        // > openssl req -newkey rsa:2048 -nodes -keyout selfcert.key -x509 -days 365 -out selfcert.crt
        // and paste selfcert.crt content below:
        private const string _myWebServerCrt =
@"-----BEGIN CERTIFICATE-----
MORETEXT
-----END CERTIFICATE-----";

        // this one is generated with the command below. We need a password.
        // > openssl rsa -des3 -in selfcert.key -out selfcertenc.key
        // the one below was encoded with '1234' as the password.
        private const string _myWebServerPrivateKey =
@"-----BEGIN RSA PRIVATE KEY-----
MORETEXTANDENCRYPTED
-----END RSA PRIVATE KEY-----";

using (WebServer server = new WebServer(443, HttpProtocol.Https)
{
    // Add a handler for commands that are received by the server.
    server.CommandReceived += ServerCommandReceived;
    server.HttpsCert = _myWebServerCertificate509;

    server.SslProtocols = System.Net.Security.SslProtocols.Tls | System.Net.Security.SslProtocols.Tls11 | System.Net.Security.SslProtocols.Tls12;
    // Start the server.
    server.Start();

    Thread.Sleep(Timeout.Infinite);
}

IMPORTANT: because the certificate above is not issued from a Certificate Authority it won't be recognized as a valid certificate. If you want to access the nanoFramework device with your browser, for example, you'll have to add the (CRT file)[WebServer.Sample\webserver-cert.crt] as a trusted one. On Windows, you just have to double click on the CRT file and then click "Install Certificate...".

You can of course use the routes as defined earlier. Both will work, event or route with the notion of controller.

Feedback and documentation

For documentation, providing feedback, issues and finding out how to contribute please refer to the Home repo.

Join our Discord community here.

Credits

The list of contributors to this project can be found at CONTRIBUTORS.

License

The nanoFramework WebServer library is licensed under the MIT license.

Code of Conduct

This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behaviour in our community. For more information see the .NET Foundation Code of Conduct.

.NET Foundation

This project is supported by the .NET Foundation.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].