Skip to content

Instantly share code, notes, and snippets.

@pimbrouwers
Forked from davidfowl/Program.cs
Last active March 17, 2020 11:41
Show Gist options
  • Select an option

  • Save pimbrouwers/4b8131a0fc312af01cb3e205423f43b2 to your computer and use it in GitHub Desktop.

Select an option

Save pimbrouwers/4b8131a0fc312af01cb3e205423f43b2 to your computer and use it in GitHub Desktop.
A minimal fully asynchronous C# ASP.NET Core 3.x application with routing
  • Copy + paste Program.cs and WebApp.csproj into a directory
  • dotnet restore
  • dotnet run
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
</Project>
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApp
{
public class Program
{
public static async Task<int> Main(string[] args) {
try {
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://localhost:5000/;https://localhost:5001")
.ConfigureServices(_configureServices)
.Configure(_configure)
.Build();
await host.RunAsync();
return 0;
}
catch {
return -1;
}
}
static Action<IServiceCollection> _configureServices = (services) => {
services.AddRouting();
};
static Action<IApplicationBuilder> _configure = app => {
app.UseRouting();
app.UseEndpoints(r => {
r.MapGet("/hello/{name}", ctx => ctx.Response.WriteAsync("hello " + ctx.Request.RouteValues["name"]));
r.MapGet("/", ctx => ctx.Response.WriteAsync("Hello World!"));
});
app.Run((ctx) => ctx.Response.WriteAsync("Page not found."));
};
}
}
@davidfowl

Copy link
Copy Markdown

This is using the old routing system. Endpoint routing is the new one linked in the original gist. It's much faster πŸ˜„

@pimbrouwers

Copy link
Copy Markdown
Author

This is using the old routing system. Endpoint routing is the new one linked in the original gist. It's much faster πŸ˜„

I preferred the API of the IRouter because it more explicitly exposed the parsed route data. But no brainer if the new Endpoint router is that much faster. Updated.

@davidfowl

Copy link
Copy Markdown

The route data is on the http request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment