This repository was archived by the owner on Nov 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 123
This repository was archived by the owner on Nov 27, 2018. It is now read-only.
Add extensions for super simple HTTP service application building #367
Copy link
Copy link
Closed
Description
Some people want to have as little code as possible in a single file (Program.cs) to stand up very simple HTTP services (no, I won't say "micro-services").
In other platforms (Go, Node, etc.) it's generally very easy to get an HTTP server up with some basic dispatching to various request-handling functions based on URL path. Doing this in ASP.NET Core today requires slightly more ceremony (Using IApplicationBuilder, RouteBuilder, a Startup class, etc.) but this can be very easily fixed with a couple of new extension methods in Routing.
Super simple HTTP service application:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
namespace NotAMicroService
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://+:8080/") // optional, we default to listening on http://localhost:5000/
.Configure(app => app
.UseRouter(router => router
.MapGet("hello/{*name}", (req, res, data) => res.WriteAsync($"Hello, {data.Values["name"]}!"))
.MapGet("goodbye/{*name}", (req, res, data) => res.WriteAsync($"Goodbye, {data.Values["name"]}!"))
.MapGet("{*name}", (req, res, data) => res.WriteAsync($"Welcome, {data.Values["name"]}!"))
)
)
.Build();
host.Run();
}
}
}Extension methods we need to add to Microsoft.AspNetCore.Routing to make this work:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Hosting
{
public static class WebHostExtensions
{
public static IWebHostBuilder UseRouter(this IWebHostBuilder builder, Action<RouteBuilder> routeBuilder)
{
return builder
.ConfigureServices(services => services.AddRouting())
.Configure(app =>
{
var router = new RouteBuilder(app);
routeBuilder(router);
app.UseRouter(router.Build());
});
}
}
}using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Microsoft.AspNetCore.Hosting
{
public static class RouteBuilderExtensions
{
public static IRouteBuilder MapGet(this IRouteBuilder builder, string template, Func<HttpRequest, HttpResponse, RouteData, Task> handler)
{
builder.MapGet(template, context =>
{
return handler(context.Request, context.Response, context.GetRouteData());
});
return builder;
}
}
}lohithgn, jaredreynolds, cklutz and henkmollemabiuboombiuboom and cklutznil4, kieranmo, kedarvaidya, dustinmoris, tabakerov and 3 more