![forthebadge](https://camo.githubusercontent.com/3ddf953b28e33578eafb773812097619d6b989465446d24b40ab8f1eb06c5277/68747470733a2f2f666f7274686562616467652e636f6d2f696d616765732f6261646765732f6d6164652d776974682d632d73686172702e737667)
![Nuget](https://camo.githubusercontent.com/452c444be563ab77f612515634030b5dcbf9b4f90938b34314ddfb805b4fdcb5/68747470733a2f2f696d672e736869656c64732e696f2f6e756765742f762f4c6567656e64617279422e4368657272792e7376673f7374796c653d666c61742d737175617265)
A simple http server implementation with a few goodies built around NET's HttpListener.
- Built around .NET's HttpListener
- Setup of the
HttpServer
instance via a fluent api
- Lightweight. The only dependency is
Microsoft.Extensions.Logging.Abstractions
to make logging of internal events possible
- Built-in
HttpRouter
is interchangeable by implementing the interface IHttpRouter
and calling HttpServer.Use<MyRouter>()
- HTTP Controller support (limited to
POST
, GET
, PUT
, DELETE
, but extendable)
- Use
Func<THttpRequest, THttpRespoonse, Task>
to implement controllers
- Middleware support
- Use
Func<THttpContext, Task>
to implement custom middlewares
namespace Cherry.ConsoleApp
{
public class User
{
public string Name => "Daniel";
public string Mail => "[email protected]";
}
public class JsonContentTypeMiddleware : IMiddleware
{
public Task HandleRequestAsync(
HttpListenerRequest req,
HttpListenerResponse res)
{
res.ContentType = MediaTypeNames.Application.Json;
return Task.CompletedTask;
}
}
public class HelloWorldController : HttpController
{
public override Task HandleGetAsync(HttpListenerRequest req, HttpListenerResponse res)
{
return res.AnswerWithStatusCodeAsync(
"Hello World!",
HttpStatusCode.OK);
}
}
[Route("/api/v1/users")]
public class UserController : HttpController
{
public override Task HandleGetAsync(HttpListenerRequest req, HttpListenerResponse res)
{
return base.HandleGetAsync(req, res);
}
}
public class Program
{
static async Task Main()
{
var server = new HttpServer(NullLogger<HttpServer>.Instance, "http://localhost:8081/")
.RegisterMiddleware<JsonContentTypeMiddleware>() // installs a global middleware because no specific route was provided
.RegisterController<HelloWorldController>("/api/v1/hello") // Path must be provided because the class is not decorated with the route attribute
.RegisterController<UserController>(); // No path must be provided, because the class is decorated with the Route attribute
// server.AutoRegisterControllers(); // Can be used to automatically discover controllers from a given assembly. Uses reflection and ignores all types which are not decorated with the Route attribute and inheriting from the HttpController base class
await server.RunAsync();
}
}
}