using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; namespace Apewer.Web { /// 响应。 public sealed class MiniResponse { bool _disposed = false; /// 上下文。 public MiniContext Context { get; private set; } /// 保持连接。 internal bool KeepAlive { get; set; } /// HTTP 状态码。 /// 默认值:200 public int Status { get; set; } /// 头。 public StringPairs Headers { get; set; } /// 内容类型。 public string ContentType { get; set; } /// 内容长度。 public long ContentLength { get; set; } /// 重定向地址。 internal string Location { get; set; } /// public Stream Body { get => Context.Connection.GetResponseStream(); } internal MiniResponse(MiniContext context) { Context = context; Headers = new StringPairs(); ContentLength = -1; Status = 200; } /// public Json ToJson() { var json = new Json(); json.SetProperty("Status", Status); json.SetProperty("Location", Location); json.SetProperty("ContentType", ContentType); json.SetProperty("ContentLength", ContentLength); json.SetProperty("Headers", Json.From(Headers)); return json; } /// 重定向到指定的 URL。 /// /// public void Redirect(string url, int status) { if (url == null) throw new ArgumentNullException(nameof(url)); url = TextUtility.Trim(url); if (url.IsEmpty()) throw new ArgumentException("参数 url 为空。"); Status = 302; Location = url; } void Close(bool force) { if (_disposed) return; _disposed = true; Context.Connection.Close(force); } /// 关闭连接。 public void Close() => Close(false); #region cookies /// 生成 Cookie 的头字段。 public static string Format(Cookie cookie) { if (cookie == null) return null; if (string.IsNullOrEmpty(cookie.Name)) return null; var segs = new List(4); if (cookie.Version > 0) segs.Add("Version=" + cookie.Version.ToString()); if (!string.IsNullOrEmpty(cookie.Name)) segs.Add(cookie.Name + "=" + (cookie.Value ?? "")); if (!string.IsNullOrEmpty(cookie.Path)) segs.Add("Path=" + cookie.Path); if (!string.IsNullOrEmpty(cookie.Domain)) segs.Add("Domain=" + cookie.Domain); if (!string.IsNullOrEmpty(cookie.Port)) segs.Add("Port=" + cookie.Port); if (segs.Count < 1) return null; var text = string.Join(";", segs.ToArray()); return text; } static string QuotedString(Cookie cookie, string value) { if (cookie.Version == 0 || IsToken(value)) return value; else return "\"" + value.Replace("\"", "\\\"") + "\""; } static bool IsToken(string value) { // from RFC 2965, 2068 const string tspecials = "()<>@,;:\\\"/[]?={} \t"; int len = value.Length; for (int i = 0; i < len; i++) { char c = value[i]; if (c < 0x20 || c >= 0x7f || tspecials.IndexOf(c) != -1) return false; } return true; } #endregion } }