public static Action<IContext, Action> Directory(string path)
{
if (String.IsNullOrWhiteSpace(path))
{
path = "/";
}
var staticRoot = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path.Replace("/", "\\").TrimStart('\\')));
return (context, next) =>
{
var res = context.Response;
var req = context.Request;
var absPath = req.Url.AbsolutePath;
var unUrlified = Uri.UnescapeDataString(absPath.Replace("/", "\\")).TrimStart('\\');
var filePath = Path.Combine(staticRoot, unUrlified);
var fullPath = Path.GetFullPath(filePath);
if (!fullPath.StartsWith(staticRoot))
{
throw new InvalidOperationException("File path disallowed.");
}
if (File.Exists(filePath))
{
FileSystem.File.ReadAllBytes(filePath, (ex, buffer) =>
{
if (ex != null)
{
res.StatusCode = 500;
res.StatusDescription = "Internal server error.";
} else
{
res.StatusCode = 200;
res.ContentType = GetMimeType(filePath);
res.Write(buffer);
}
res.Send();
});
} else
{
next();
}
};
}