[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=nanoframework_lib-nanoframework.WebServer&metric=alert_status)](https://sonarcloud.io/dashboard?id=nanoframework_lib-nanoframework.WebServer) [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=nanoframework_lib-nanoframework.WebServer&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=nanoframework_lib-nanoframework.WebServer) [![NuGet](https://img.shields.io/nuget/dt/nanoFramework.WebServer.svg?label=NuGet&style=flat&logo=nuget)](https://www.nuget.org/packages/nanoFramework.WebServer/) [![#yourfirstpr](https://img.shields.io/badge/first--timers--only-friendly-blue.svg)](https://github.com/nanoframework/Home/blob/main/CONTRIBUTING.md) [![Discord](https://img.shields.io/discord/478725473862549535.svg?logo=discord&logoColor=white&label=Discord&color=7289DA)](https://discord.gg/gCyBu8T) ![nanoFramework logo](https://raw.githubusercontent.com/nanoframework/Home/main/resources/logo/nanoFramework-repo-logo.png) ----- ### Welcome to the .NET **nanoFramework** WebServer repository ## Build status | Component | Build Status | NuGet Package | |:-|---|---| | nanoFramework.WebServer | [![Build Status](https://dev.azure.com/nanoframework/nanoFramework.WebServer/_apis/build/status/nanoFramework.WebServer?repoName=nanoframework%2FnanoFramework.WebServer&branchName=main)](https://dev.azure.com/nanoframework/nanoFramework.WebServer/_build/latest?definitionId=65&repoName=nanoframework%2FnanoFramework.WebServer&branchName=main) | [![NuGet](https://img.shields.io/nuget/v/nanoFramework.WebServer.svg?label=NuGet&style=flat&logo=nuget)](https://www.nuget.org/packages/nanoFramework.WebServer/) | | nanoFramework.WebServer.FileSystem | [![Build Status](https://dev.azure.com/nanoframework/nanoFramework.WebServer/_apis/build/status/nanoFramework.WebServer?repoName=nanoframework%2FnanoFramework.WebServer&branchName=main)](https://dev.azure.com/nanoframework/nanoFramework.WebServer/_build/latest?definitionId=65&repoName=nanoframework%2FnanoFramework.WebServer&branchName=main) | [![NuGet](https://img.shields.io/nuget/v/nanoFramework.WebServer.FileSystem.svg?label=NuGet&style=flat&logo=nuget)](https://www.nuget.org/packages/nanoFramework.WebServer.FileSystem/) | ## .NET nanoFramework WebServer This library was coded by [Laurent Ellerbach](https://github.com/Ellerbach) who generously offered it to the .NET **nanoFramework** project. This is a simple nanoFramework WebServer. Features: - Handle multi-thread requests - Serve static files from any storage using [`nanoFramework.WebServer.FileSystem` NuGet](https://www.nuget.org/packages/nanoFramework.WebServer.FileSystem). Requires a target device with support for storage (having `System.IO.FileSystem` capability). - 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](https://github.com/nanoframework/lib-nanoFramework.System.Net.Http/blob/develop/nanoFramework.System.Net.Http/Http/System.Net.HttpUtility.cs) 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. ```csharp 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. ```csharp 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: ```csharp 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 `RouteAnyTest`is 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](./WebServer.Sample/ControllerPerson.cs). > [!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](https://github.com/nanoframework/Samples/tree/main/samples/Webserver/WebServer.GpioRest) REST API. The controller not case sensitive and is working like this: - To open the pin 2 as output: http://yoururl/open/2/output - To open pin 4 as input: http://yoururl/open/4/input - To write the value high to pin 2: http://yoururl/write/2/high - You can use high or 1, it has the same effect and will place the pin in high value - You can use low of 0, it has the same effect and will place the pin in low value - To read the pin 4: http://yoururl/read/4, you will get as a raw text `high`or `low`depending on the state ## 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: ```csharp [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: ```csharp 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. The webserver supports having multiple authentication methods or credentials for the same route. Each pair of authentication method plus credentials should have its own method in the controller: ```csharp class MixedController { [Route("sameroute")] [Authentication("Basic")] public void Basic(WebServerEventArgs e) { WebServer.OutPutStream(e.Context.Response, "sameroute: Basic"); } [Authentication("ApiKey:superKey1234")] [Route("sameroute")] public void Key(WebServerEventArgs e) { WebServer.OutPutStream(e.Context.Response, "sameroute: API key #1"); } [Authentication("ApiKey:superKey5678")] [Route("sameroute")] public void Key2(WebServerEventArgs e) { WebServer.OutPutStream(e.Context.Response, "sameroute: API key #2"); } [Route("sameroute")] public void None(WebServerEventArgs e) { WebServer.OutPutStream(e.Context.Response, "sameroute: Public"); } } ``` The webserver selects the route for a request: - If there are no matching methods, a not-found response (404) is returned. - If authentication information is passed in the header of the request, then only methods that require authentication are considered. If one of the method's credentials matches the credentials passed in the request, that method is called. Otherwise a non-authorized response (401) will be returned. - If no authentication information is passed in the header of the request: - If one of the methods does not require authentication, that method is called. - Otherwise a non-authorized response (401) will be returned. If one of the methods requires basic authentication, the `WWW-Authenticate` header is included to request credentials. The webserver does not support more than one matching method. Calling multiple methods most likely results in an exception as a subsequent method tries to modify a response that is already processed by the first method. The webserver does not know what to do and returns an internal server error (500). The body of the response lists the matching methods. Having multiple matching methods is considered a programming error. One way this occurs is if two methods in a controller accidentally have the same route. Returning an internal server error with the names of the methods makes it easy to discover the error. It is expected that the error is discovered and fixed in testing. Then the internal error will not occur in the application that is deployed to a device. ## Managing incoming queries thru events Very basic usage is the following: ```csharp 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: ```csharp WebServer.OutPutStream(e.Context.Response, "
" + "