/// <summary> /// 将流分析成Header集合和Body内存流 /// </summary> /// <param name="_out"></param> /// <returns></returns> public static HttpInfo Parse(Stream _out) { var info = new HttpInfo(); int position = 0; string firstLine = ""; info.Headers = ParseHeader(_out, ref position, ref firstLine); info.FirstLine = firstLine; info.Content = ToMemStream(_out); return info; }
/// <summary> /// 缓存没过期,直接输出缓存 /// </summary> /// <param name="context"></param> /// <param name="key"></param> /// <param name="info"></param> private void ResponceCache(HttpContext context, string key, CacheInfo info) { var req = context.Request; var rep = context.Response; string time = info.StoreTime.ToString("r"); if (req.Headers["If-Modified-Since"] == time) { rep.StatusCode = (int)System.Net.HttpStatusCode.NotModified; LogHelp.Info("cache hit 304 " + req.RawUrl); } else { var httpInfo = new HttpInfo(); var _stream = Store.Get(key); int headEndPosition = 0; string firstLine = ""; httpInfo.Headers = HttpParseHelp.ParseHeader(_stream, ref headEndPosition, ref firstLine); rep.StatusCode = ParseRespondCode(firstLine); if (rep.StatusCode == 200) { rep.AppendHeader("Last-Modified", time); } httpInfo.Content = _stream; OutResponse(req, rep, httpInfo); LogHelp.Info("cache hit html " + req.RawUrl); } context.ApplicationInstance.CompleteRequest(); }
/// <summary> /// 输出http响应header /// </summary> /// <param name="rep"></param> /// <param name="info"></param> private void OutHeaders(HttpResponse rep, HttpInfo info) { foreach (var item in info.Headers) { if (alowHeader.Contains(item.Name)) { rep.AppendHeader(item.Name, item.Value.TrimEnd()); } } }
/// <summary> /// 输出Http流 /// </summary> /// <param name="rep"></param> /// <param name="info"></param> private void OutResponse(HttpRequest req, HttpResponse rep, HttpInfo info) { Stream _out = AcceptGzip(req, rep, info); OutHeaders(rep, info); OutBody(rep, _out); }
/// <summary> /// 根据请求头自动判断客户端是否支持gzip,如果不支持, 在服务器解压 /// </summary> /// <param name="req"></param> /// <param name="rep"></param> /// <param name="info"></param> /// <returns></returns> private static Stream AcceptGzip(HttpRequest req, HttpResponse rep, HttpInfo info) { var acceptEncoding = req.Headers.Get("Accept-Encoding"); Stream _out; if (acceptEncoding != null && acceptEncoding.Contains("gzip")) { _out = info.Content; rep.AppendHeader("Content-Encoding", "gzip"); } else { _out = new GZipStream(info.Content, CompressionMode.Decompress); } return _out; }