When developing HTML/JS applications and testing locally (file:///c:/...), browsers often block certain features such as accessing local files via XMLHttpRequest. In Google Chrome, you can disable this check using the command-line argument --allow-file-access-from-files, but doing so compromises your browser's security. A better approach is to run a basic local web server to serve static files. Since I need to do this frequently, I added a shortcut to the Windows Explorer context menu.
Final result
- Create a .NET Core console application
- Reference the following NuGet packages:
Microsoft.AspNetCore, Microsoft.AspNetCore.StaticFiles and Microsoft.Win32.Registry - Create the web server with default files and directory browsing
C#
class Program
{
static void Main(string[] args)
{
var path = Directory.GetCurrentDirectory();
if (args.Length > 0)
{
path = args[0];
}
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(path)
.UseWebRoot(path)
.UseUrls("http://localhost:5000")
.UseStartup<Startup>()
.Build();
host.Run();
}
}
internal class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Information);
var fileServerOptions = new FileServerOptions();
fileServerOptions.EnableDefaultFiles = true;
fileServerOptions.EnableDirectoryBrowsing = true;
fileServerOptions.FileProvider = env.WebRootFileProvider;
fileServerOptions.StaticFileOptions.ServeUnknownFileTypes = true;
app.UseFileServer(fileServerOptions);
}
}
Now, you can start the application and access the content of the directory using http://localhost:5000. For debugging purposes, each request is logged in the console.
If you are using Windows, you can add an item to the Windows Explorer context menu to directly start the web server:
C#
static void RegisterContextMenu()
{
string location = Assembly.GetEntryAssembly().Location;
using (var key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Classes\Directory\shell\FileServer"))
{
key.SetValue("", "Open with FileServer", RegistryValueKind.String);
key.SetValue("Icon", location, RegistryValueKind.String);
using (var commandKey = key.CreateSubKey("command"))
{
if (location.EndsWith(".dll"))
{
commandKey.SetValue("", "\"C:\\Program Files\\dotnet\\dotnet.exe\" \"" + location + "\" \"%V\"", RegistryValueKind.String);
}
else
{
commandKey.SetValue("", "\"" + location + "\" \"%V\"", RegistryValueKind.String);
}
}
}
}
Do you have a question or a suggestion about this post? Contact me!