using System; using System.IO; using System.Net; namespace NetCoreServer { /// /// HTTPS server is used to create secured HTTPS Web server and communicate with clients using secure HTTPS protocol. It allows to receive GET, POST, PUT, DELETE requests and send HTTP responses. /// /// Thread-safe. public class HttpsServer : SslServer { /// /// Initialize HTTPS server with a given IP address and port number /// /// SSL context /// IP address /// Port number public HttpsServer(SslContext context, IPAddress address, int port) : base(context, address, port) { Cache = new FileCache(); } /// /// Initialize HTTPS server with a given IP address and port number /// /// SSL context /// IP address /// Port number public HttpsServer(SslContext context, string address, int port) : base(context, address, port) { Cache = new FileCache(); } /// /// Initialize HTTPS server with a given DNS endpoint /// /// SSL context /// DNS endpoint public HttpsServer(SslContext context, DnsEndPoint endpoint) : base(context, endpoint) { Cache = new FileCache(); } /// /// Initialize HTTPS server with a given IP endpoint /// /// SSL context /// IP endpoint public HttpsServer(SslContext context, IPEndPoint endpoint) : base(context, endpoint) { Cache = new FileCache(); } /// /// Get the static content cache /// public FileCache Cache { get; } /// /// Add static content cache /// /// Static content path /// Cache prefix (default is "/") /// Cache filter (default is "*.*") /// Refresh cache timeout (default is 1 hour) public void AddStaticContent(string path, string prefix = "/", string filter = "*.*", TimeSpan? timeout = null) { timeout ??= TimeSpan.FromHours(1); bool Handler(FileCache cache, string key, byte[] value, TimeSpan timespan) { var response = new HttpResponse(); response.SetBegin(200); response.SetContentType(Path.GetExtension(key)); response.SetHeader("Cache-Control", $"max-age={timespan.Seconds}"); response.SetBody(value); return cache.Add(key, response.Cache.Data, timespan); } Cache.InsertPath(path, prefix, filter, timeout.Value, Handler); } /// /// Remove static content cache /// /// Static content path public void RemoveStaticContent(string path) { Cache.RemovePath(path); } /// /// Clear static content cache /// public void ClearStaticContent() { Cache.Clear(); } protected override SslSession CreateSession() { return new HttpsSession(this); } #region IDisposable implementation // Disposed flag. private bool _disposed; protected override void Dispose(bool disposingManagedResources) { if (!_disposed) { if (disposingManagedResources) { // Dispose managed resources here... Cache.Dispose(); } // Dispose unmanaged resources here... // Set large fields to null here... // Mark as disposed. _disposed = true; } // Call Dispose in the base class. base.Dispose(disposingManagedResources); } // The derived class does not have a Finalize method // or a Dispose method without parameters because it inherits // them from the base class. #endregion } }