A Simple .NET CLI Web Server

Locally, I’ve been running some simple HTML, CSS, and JavaScript websites, as well as the static output of Hugo (my blog engine).

When I wanted to serve these sites, I used to call python -m http.server in the directory where the files were. It’s easy, but in the last few months, I’ve been writing more of the dotnet run app.cs style applications, and it is perfect for a web server.

The code is not very complicated, and it works well.

Make sure the .cs file has execution permissions, and then you can run it withwebserver /path/to/files and it will serve the files in that directory on port 8080. You can also specify the port with webserver /path/to/files 8081 if you want to use something other than port 8080.

 1#!/usr/bin/dotnet run
 2#:sdk Microsoft.NET.Sdk.Web
 3
 4using Microsoft.AspNetCore.StaticFiles;
 5using Microsoft.Extensions.FileProviders;
 6
 7var webRoot = args.Length > 0 ? Path.GetFullPath(args[0]) : Directory.GetCurrentDirectory();
 8
 9var port = args.Length > 1 && int.TryParse(args[1], out var p) ? p : 8080;
10
11if (!Directory.Exists(webRoot))
12{
13    Console.Error.WriteLine($"Error: directory not found: {webRoot}");
14    return 1;
15}
16
17var builder = WebApplication.CreateBuilder(args);
18builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
19builder.Logging.SetMinimumLevel(LogLevel.Warning);
20
21var app = builder.Build();
22
23var provider = new PhysicalFileProvider(webRoot);
24
25var defaultFiles = new DefaultFilesOptions
26{
27    FileProvider = provider,
28    DefaultFileNames = {"index.html", "index.htm", "home.html", "home.htm", "default.html", "default.htm"},
29};
30
31app.UseDefaultFiles(defaultFiles);
32
33app.UseStaticFiles(new StaticFileOptions
34{
35    FileProvider = provider,
36    ContentTypeProvider = new FileExtensionContentTypeProvider(),
37    ServeUnknownFileTypes = true,
38    DefaultContentType = "application/octet-stream",
39    OnPrepareResponse = context =>
40    {
41        Console.WriteLine($"{context.Context.Request.Method} {context.Context.Request.Path}");
42    }
43});
44
45app.UseDirectoryBrowser(new DirectoryBrowserOptions
46{
47    FileProvider = provider,
48});
49
50Console.WriteLine($"Serving: {webRoot}");
51Console.WriteLine($"Listening on: http://127.0.0.1:{port}");
52
53app.Run();
54return 0;

The more I use this .NET CLI, the more I find uses for it.

comments powered by Disqus

Related