EonaCat.Network/EonaCat.Network/System/Sockets/Web/Server/HttpRequestEventArgs.cs

102 lines
2.7 KiB
C#

// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using System;
using System.IO;
using System.Security.Principal;
using System.Text;
namespace EonaCat.Network
{
public class HttpRequestEventArgs : EventArgs
{
private readonly HttpListenerContext _context;
private readonly string _docRootPath;
internal HttpRequestEventArgs(
HttpListenerContext context, string documentRootPath
)
{
_context = context;
_docRootPath = documentRootPath;
}
public HttpListenerRequest Request => _context.Request;
public HttpListenerResponse Response => _context.Response;
public IPrincipal User => _context.User;
public byte[] ReadFile(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (path.Length == 0)
{
throw new ArgumentException("An empty string.", nameof(path));
}
if (path.IndexOf("..") > -1)
{
throw new ArgumentException("It contains '..'.", nameof(path));
}
tryReadFile(createFilePath(path), out byte[] contents);
return contents;
}
public bool TryReadFile(string path, out byte[] contents)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (path.Length == 0)
{
throw new ArgumentException("An empty string.", nameof(path));
}
if (path.IndexOf("..") > -1)
{
throw new ArgumentException("It contains '..'.", nameof(path));
}
return tryReadFile(createFilePath(path), out contents);
}
private static bool tryReadFile(string path, out byte[] contents)
{
contents = null;
if (!File.Exists(path))
{
return false;
}
try
{
contents = File.ReadAllBytes(path);
}
catch
{
return false;
}
return true;
}
private string createFilePath(string childPath)
{
childPath = childPath.TrimStart('/', '\\');
return new StringBuilder(_docRootPath, 32)
.AppendFormat("/{0}", childPath)
.ToString()
.Replace('\\', '/');
}
}
}