private bool CrossDomainXmlHandler(HttpListenerContext context) { HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; if (request.Url.AbsolutePath.ToLower() == "/crossdomain.xml") { if (request.Headers["If-Modified-Since"] == lastModified && request.Headers["If-None-Match"] == etag) { response.StatusCode = 304; } else { byte[] crossDomainXml = Encoding.ASCII.GetBytes(crossDomainXmlContent); response.AppendHeader("Last-Modified", lastModified); response.AppendHeader("Etag", etag); response.ContentType = "text/xml"; response.ContentLength64 = crossDomainXml.Length; response.SendChunked = false; response.OutputStream.Write(crossDomainXml, 0, crossDomainXml.Length); response.OutputStream.Flush(); } response.Close(); return(true); } return(false); }
public static void WaitForConnections() { listener.Prefixes.Add("http://*:" + Port + "/"); listener.Start(); Thread iconthread = new Thread(() => createIcon(true)); iconthread.Name = "IconThread"; iconthread.Start(); while (true) { while (true) { HttpListenerContext s = listener.GetContext(); HttpListenerResponse response = s.Response; if (BanList.Contains(s.Request.RemoteEndPoint.Address.ToString())) { response.Abort(); continue; } response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, user, password"); response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); response.AppendHeader("Access-Control-Allow-Origin", "*"); response.AppendHeader("Content-Type", "text/plain;charset=UTF-8"); response.ContentEncoding = Encoding.UTF8; totalconnections++; SpawnNewClient = new Thread(() => NewClient(s)); SpawnNewClient.Start(); } } }
private bool ClientAccessPolicyXmlHandler(HttpListenerContext context) { HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; if (request.Url.AbsolutePath.ToLower() == "/clientaccesspolicy.xml") { if (request.Headers["If-Modified-Since"] == lastModified && request.Headers["If-None-Match"] == etag) { response.StatusCode = 304; } else { #if !dotNETMF response.AppendHeader("Last-Modified", lastModified); response.AppendHeader("Etag", etag); #else response.Headers.Add("Last-Modified", lastModified); response.Headers.Add("Etag", etag); #endif response.ContentType = "text/xml"; response.ContentLength64 = clientAccessPolicyXml.Length; response.SendChunked = false; response.OutputStream.Write(clientAccessPolicyXml, 0, clientAccessPolicyXml.Length); response.OutputStream.Flush(); } response.Close(); return(true); } return(false); }
public async Task AppendHeader_InvalidNameOrValue_ThrowsArgumentException() { HttpListenerResponse response = await GetResponse(); AssertExtensions.Throws <ArgumentException>("name", () => response.AppendHeader("\r \t \n", "")); AssertExtensions.Throws <ArgumentException>("name", () => response.AppendHeader("(", "")); AssertExtensions.Throws <ArgumentException>("value", () => response.AppendHeader("name", "value1\rvalue2\r")); }
private void SetCorsHeaders(HttpListenerResponse response) { response.AppendHeader("Access-Control-Allow-Origin", "*"); response.AppendHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS"); response.AppendHeader("Access-Control-Allow-Credentials", "false"); response.AppendHeader("Access-Control-Max-Age", "86400"); response.AppendHeader("Access-Control-Allow-Headers", "*"); }
public async Task AppendHeader_ValidValue_AddsHeaderToCollection() { HttpListenerResponse response = await GetResponse(); response.AppendHeader("name", "value1"); Assert.Equal("value1", response.Headers["name"]); response.AppendHeader("name", "value2"); Assert.Equal("value1,value2", response.Headers["name"]); }
private void Worker() { while (WaitHandle.WaitAny(new WaitHandle[] { m_Ready, m_Stop }) == 0) { HttpListenerContext ctx; lock (m_Queue) { if (m_Queue.Count > 0) { ctx = m_Queue.Dequeue(); } else { m_Ready.Reset(); continue; } } if (OnRequestReceived != null) { HttpListenerRequest request = ctx.Request; string str = OnRequestReceived(); byte[] buf = Encoding.UTF8.GetBytes(str); HttpListenerResponse response = ctx.Response; response.AppendHeader("Access-Control-Allow-Origin", "*"); response.AppendHeader("Cache-Control", "no-cache"); response.KeepAlive = false; string callback = request.QueryString["callback"]; if (string.IsNullOrEmpty(callback)) { response.ContentType = "application/json"; response.ContentLength64 = buf.Length; } else { str = string.Format("if ({0} != undefined) {{ {0}({1}) }};", callback, str); buf = Encoding.UTF8.GetBytes(str); response.ContentType = "application/javascript"; response.ContentLength64 = buf.Length; } Stream output = response.OutputStream; output.Write(buf, 0, buf.Length); output.Close(); } } }
private async void Process(HttpListener listener) { listener.Start(); Program.Print(string.Format("[INFO] JSON-API service started at {0}...", listener.Prefixes.ElementAt(0))); m_isOngoing = true; while (m_isOngoing) { HttpListenerContext context = null; try { context = await listener.GetContextAsync(); } catch (HttpListenerException ex) { if (ex.ErrorCode == 995) { break; } Program.Print(string.Format("[ERROR] {0}: Error code: {1}, Message: {2}", ex.GetType().Name, ex.ErrorCode, ex.Message)); await Task.Delay(1000); continue; } catch (ObjectDisposedException) { break; } catch (Exception ex) { Program.Print(string.Format("[ERROR] {0}", ex.Message)); await Task.Delay(1000); continue; } HttpListenerResponse response = context.Response; if (response != null) { response.AppendHeader("Pragma", "no-cache"); response.AppendHeader("Expires", "0"); response.ContentType = "application/json"; response.StatusCode = (int)HttpStatusCode.OK; ProcessApiDataResponse(response); } } }
private void SendJSON(HttpListenerResponse response) { response.AppendHeader("Access-Control-Allow-Origin", "*"); // allow access from the same hostname string JSON = "{\"id\": 0, \"Text\": \"Sensor\", \"Children\": ["; nodeCount = 1; JSON += GenerateJSON(root); JSON += "]"; JSON += ", \"Min\": \"Min\""; JSON += ", \"Value\": \"Value\""; JSON += ", \"Max\": \"Max\""; JSON += ", \"ImageURL\": \"\""; JSON += "}"; var responseContent = JSON; byte[] buffer = Encoding.UTF8.GetBytes(responseContent); response.AddHeader("Cache-Control", "no-cache"); response.ContentLength64 = buffer.Length; response.ContentType = "application/json"; try { Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } catch (HttpListenerException) { } response.Close(); }
private void ServerHandler() { while (working) { HttpListenerContext context = server.GetContext(); HttpListenerResponse response = context.Response; response.ContentType = "application/json"; response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); response.AppendHeader("Access-Control-Allow-Origin", "*"); string something = "["; //用迴圈取得多個裝置 int cnt = joyconManager.j.Count; for (int i = 0; i < cnt; i++) { var j = joyconManager.j[i]; something += JoyconToString(j); if (i != cnt - 1) { something += ","; } } something += "]"; byte[] buffer = Encoding.UTF8.GetBytes(something); response.ContentLength64 = buffer.Length; Stream st = response.OutputStream; st.Write(buffer, 0, buffer.Length); context.Response.Close(); Thread.Sleep(1); } }
/// <summary> /// Set the e-tag /// </summary> /// <param name="isWeak">True if the e-tag is a weak reference</param> /// <param name="etag">The value of the e-tag</param> public static void SetETag(this HttpListenerResponse me, String etag, bool isWeak = false) { if (!String.IsNullOrEmpty(etag)) { me.AppendHeader("ETag", isWeak ? $"W/{etag}" : etag); } }
private async Task <byte[]> GetSerializedResponseData(object data, HttpListenerResponse httpResponse) { if (data is null) { throw new System.Exception("Data can't be NULL"); } else if (data is string message) { return(Encoding.UTF8.GetBytes(message)); } else if (data is ViewModel viewModel) { var bodyTask = TempleteResolver?.Resolve(viewModel); return(Encoding.UTF8.GetBytes(await bodyTask.ConfigureAwait(false))); } else if (data is Response response) { foreach (var key in response.Header.Keys) { httpResponse.AppendHeader(key, response.Header[key]); } httpResponse.StatusCode = response.StatusCode; return(await GetSerializedResponseData(response.Model, httpResponse).ConfigureAwait(false)); } else if (data is Task task) { await task.ConfigureAwait(false); return(await GetSerializedResponseData(TaskUtil.GetResultFromTask(task), httpResponse).ConfigureAwait(false)); } else { return(Serializer.Serialize(data)); } }
private static async Task WriteAsync(this HttpListenerResponse response, HttpStatusCode statusCode, string message) { if (string.IsNullOrEmpty(message)) { ASF.ArchiLogger.LogNullError(nameof(message)); return; } try { if (response.StatusCode != (ushort)statusCode) { response.StatusCode = (ushort)statusCode; } response.AppendHeader("Access-Control-Allow-Origin", "null"); Encoding encoding = Encoding.UTF8; response.ContentEncoding = encoding; response.ContentType = "text/plain; charset=" + encoding.WebName; byte[] buffer = encoding.GetBytes(message + Environment.NewLine); response.ContentLength64 = buffer.Length; await response.OutputStream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false); } catch (Exception e) { response.StatusCode = (ushort)HttpStatusCode.InternalServerError; ASF.ArchiLogger.LogGenericDebugException(e); } }
private void SetCookies(bool userPresent, string username) { if (userPresent) { var edded = SessionsRepo.AddSession(username); var cookie = new Cookie("SESS_ID", edded.Item1, "/", "api.sharkbank.ru"); cookie.Expires = edded.Item2; currentResponse.AppendHeader("X-CSRF-Token", edded.Item3); currentResponse.SetCookie(cookie); currentResponse.StatusCode = 200; } else { currentResponse.StatusCode = 401; } }
private void ServeResourceImage(HttpListenerResponse response, string name) { name = "OpenHardwareMonitor.Resources." + name; response.AppendHeader("Access-Control-Allow-Origin", "*"); // allow access from the same hostname string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\\', '.') == name) { using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream(names[i])) { Image image = Image.FromStream(stream); response.ContentType = "image/png"; try { Stream output = response.OutputStream; using (MemoryStream ms = new MemoryStream()) { image.Save(ms, ImageFormat.Png); ms.WriteTo(output); } output.Close(); } catch (HttpListenerException) { } image.Dispose(); response.Close(); return; } } } response.StatusCode = 404; response.Close(); }
public void Handle(HttpListenerRequest request, HttpListenerResponse response) { using (var ms = new MemoryStream()) { if (request.HttpMethod == "OPTIONS") { response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); response.AddHeader("Access-Control-Max-Age", "1728000"); } response.AppendHeader("Access-Control-Allow-Origin", "*"); request.InputStream.CopyTo(ms); var content = Encoding.UTF8.GetString(ms.ToArray()); var registrationModel = JObject.Parse(content); var session = registrationModel["session"].ToString(); var user = _sessionManagementService.GetUserBySession(session); var chatIds = _dbContext.ApplicationUserChatRooms.Where(p => p.ApplicationUserId == user).ToList(); List <string> Chats = new List <string>(); foreach (var id in chatIds) { Chats.Add(_dbContext.ChatRooms.FirstOrDefault(p => p.Id == id.ChatRoomId).Title); } response.StatusCode = 200; var json = JsonConvert.SerializeObject(Chats); response.OutputStream.Write(Encoding.UTF8.GetBytes(json)); response.Close(); } }
private void HandleOptions(HttpListenerResponse response) { response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); response.AddHeader("Access-Control-Allow-Methods", "POST"); response.AddHeader("Access-Control-Max-Age", "1728000"); response.AppendHeader("Access-Control-Allow-Origin", "*"); response.Close(); }
static void ErrorResponse(HttpListenerResponse response, Int32 status, Exception e) { response.StatusCode = 200; response.ContentType = "text/plain"; var content = Encoding.Unicode.GetBytes(e.ToString() + "\n"); response.AppendHeader("Content-Length", content.Length.ToString()); response.OutputStream.Write(content, 0, content.Length); }
private void SendResponse(string acceptType, List <OrderFields> data, HttpListenerResponse response) { var memoryStream = new MemoryStream(); if (acceptType != null) { switch (acceptType) { case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { _converter.ToExcel(data, memoryStream); response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); break; } case "text/xml": { _converter.ToXmlFormat(data, memoryStream); response.AppendHeader("Content-Type", "text/xml"); break; } case "application/xml": { _converter.ToXmlFormat(data, memoryStream); response.AppendHeader("Content-Type", "application/xml"); break; } default: { _converter.ToExcel(data, memoryStream); response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); break; } } response.StatusCode = (int)HttpStatusCode.OK; memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.WriteTo(response.OutputStream); memoryStream.Close(); response.OutputStream.Close(); } }
/// <summary> /// Send response. /// </summary> /// <param name="accept"></param> /// <param name="data"></param> /// <param name="response"></param> private void SendResponse(string accept, List <OrderView> data, HttpListenerResponse response) { using (var memoryStream = new MemoryStream()) { if (accept != null) { switch (accept) { case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { _converter.ToExcelFormat(data, memoryStream); response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.AppendHeader("Content-Disposition", "attachment; filename=translationText.xlsx;"); break; } case "text/xml": { _converter.ToXmlFormat(data, memoryStream); response.AppendHeader("Content-Type", "text/xml"); response.AppendHeader("Content-Disposition", "attachment; filename=translationText.xml"); break; } case "application/xml": { _converter.ToXmlFormat(data, memoryStream); response.AppendHeader("Content-Type", "application/xml"); response.AppendHeader("Content-Disposition", "attachment; filename=translationText.xml"); break; } default: { _converter.ToExcelFormat(data, memoryStream); response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.AppendHeader("Content-Disposition", "attachment; filename=translationText.xlsx"); break; } } } response.StatusCode = (int)HttpStatusCode.OK; memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.WriteTo(response.OutputStream); response.OutputStream.Flush(); response.OutputStream.Close(); } }
private async static void Process(HttpListener listener) { listener.Start(); Log(Level.Info, $"API service started at {listener.Prefixes.ElementAt(0)}..."); _IsOngoing = true; while (_IsOngoing) { HttpListenerContext context = null; try { context = await listener.GetContextAsync(); } catch (HttpListenerException ex) { if (ex.ErrorCode == 995) { break; // connection likely closed } Log(Level.Error, $"{ex.GetType().Name}: Error code: {ex.ErrorCode}, Message: {ex.Message}"); await Task.Delay(1000); continue; } catch (ObjectDisposedException) { break; } catch (Exception ex) { Log(ex); await Task.Delay(1000); continue; } HttpListenerResponse response = context.Response; if (response != null) { response.AppendHeader("Pragma", "no-cache"); response.AppendHeader("Expires", "0"); response.ContentType = "application/json"; response.StatusCode = (int)HttpStatusCode.OK; ProcessApiDataResponse(response); } } }
public void send(string msg) { http_response.AppendHeader("Access-Control-Allow-Origin", "*"); Stream output = http_response.OutputStream; output.Write(Encoding.UTF8.GetBytes(msg)); output.Dispose(); //send http_response.Close(); }
public void Handle(HttpListenerRequest request, HttpListenerResponse response) { using (var ms = new MemoryStream()) { if (request.HttpMethod == "OPTIONS") { response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); response.AddHeader("Access-Control-Max-Age", "1728000"); } response.AppendHeader("Access-Control-Allow-Origin", "*"); request.InputStream.CopyTo(ms); var content = Encoding.UTF8.GetString(ms.ToArray()); var registrationModel = JObject.Parse(content); var title = registrationModel["Title"].ToString(); ChatRoomType chatRoomType; Enum.TryParse(registrationModel["ChatRoomType"].ToString(), out chatRoomType); var selUsers = registrationModel["SelUsers"].ToString(); string result = new string(selUsers.Where(p => char.IsDigit(p)).ToArray()); List <int> usersId = new List <int>(); foreach (var item in result) { usersId.Add(int.Parse(item.ToString())); } _dbContext.ChatRooms.Add(new Models.ChatRoom() { Title = title, ChatRoomType = chatRoomType }); _dbContext.SaveChanges(); int chatRoomId = _dbContext.ChatRooms.FirstOrDefault(p => p.Title == title).Id; foreach (var item in usersId) { _dbContext.ApplicationUserChatRooms.Add(new Models.ApplicationUserChatRoomJunction() { ChatRoomId = chatRoomId, ApplicationUserId = item, ApplicationUserStatus = 0 }); } _dbContext.SaveChanges(); response.StatusCode = 200; response.OutputStream.Write(Encoding.UTF8.GetBytes("OK!")); response.Close(); } }
public async Task SendResponseHttpAsync(int status, string response, HttpListenerContext context) { HttpListenerResponse http_response = context.Response; http_response.AppendHeader("Access-Control-Allow-Origin", "*"); http_response.StatusCode = status; http_response.ContentType = "text/html"; using (StreamWriter writer = new StreamWriter(http_response.OutputStream, Encoding.UTF8)) await writer.WriteLineAsync(response); http_response.Close(); }
private void ListenerHandle(IAsyncResult result) { try { _listener = result.AsyncState as HttpListener; if (_listener.IsListening) { _listener.BeginGetContext(ListenerHandle, result); HttpListenerContext context = _listener.EndGetContext(result); //解析Request请求 HttpListenerRequest request = context.Request; string content = ""; switch (request.HttpMethod) { case "POST": { Stream stream = context.Request.InputStream; StreamReader reader = new StreamReader(stream, Encoding.UTF8); content = reader.ReadToEnd(); } break; case "GET": { var data = request.QueryString; } break; } WriteToStatus("收到数据:" + content + request.RawUrl); //构造Response响应 HttpListenerResponse response = context.Response; response.StatusCode = 200; response.ContentType = "application/json;charset=UTF-8"; response.ContentEncoding = Encoding.UTF8; response.AppendHeader("Content-Type", "application/json;charset=UTF-8"); using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) { writer.Write("Rep:" + DateTime.Now.ToString()); writer.Close(); response.Close(); } } } catch (Exception ex) { WriteToStatus(ex.Message); _listener.EndGetContext(result); checkListen_Checked(null, null); } }
private static async Task ResponseBase(HttpListenerRequest request, HttpListenerResponse response, byte[] content, HttpStatusCode statusCode = HttpStatusCode.OK) { if ((request == null) || (response == null) || (content == null) || (content.Length == 0)) { ASF.ArchiLogger.LogNullError(nameof(request) + " || " + nameof(response) + " || " + nameof(content)); return; } try { if (response.StatusCode != (ushort)statusCode) { response.StatusCode = (ushort)statusCode; } response.AppendHeader("Access-Control-Allow-Origin", "*"); if (CompressableContentTypes.Contains(response.ContentType)) { string acceptEncoding = request.Headers["Accept-Encoding"]; if (!string.IsNullOrEmpty(acceptEncoding)) { if (acceptEncoding.Contains("gzip")) { response.AddHeader("Content-Encoding", "gzip"); using (MemoryStream ms = new MemoryStream()) { using (GZipStream stream = new GZipStream(ms, CompressionMode.Compress)) { await stream.WriteAsync(content, 0, content.Length).ConfigureAwait(false); } content = ms.ToArray(); } } else if (acceptEncoding.Contains("deflate")) { response.AddHeader("Content-Encoding", "deflate"); using (MemoryStream ms = new MemoryStream()) { using (DeflateStream stream = new DeflateStream(ms, CompressionMode.Compress)) { await stream.WriteAsync(content, 0, content.Length).ConfigureAwait(false); } content = ms.ToArray(); } } } } response.ContentLength64 = content.Length; await response.OutputStream.WriteAsync(content, 0, content.Length).ConfigureAwait(false); } catch (ObjectDisposedException) { // Ignored, request is no longer valid } }
static void Main(string[] args) { try { HttpListener listener = new HttpListener(); listener.Prefixes.Add(LISTENER_URL); listener.Start(); Console.WriteLine("开始监听:" + LISTENER_URL); while (true) { try { HttpListenerContext context = listener.GetContext(); //阻塞 HttpListenerRequest request = context.Request; Console.WriteLine("收到请求:" + request.Url); string input = request.Url.Query; string urlpath = request.Url.LocalPath; NameValueCollection query = HttpUtility.ParseQueryString(input); HttpListenerResponse response = context.Response; //响应 response.AppendHeader("Access-Control-Allow-Origin", "*"); string responseBody = ""; try { responseBody = Api.GetResponse(urlpath, query); } catch (Exception ex) { responseBody = ex.Message; } response.ContentLength64 = Encoding.UTF8.GetByteCount(responseBody); response.ContentType = "text/html; Charset=UTF-8"; // 输出响应内容 Stream output = response.OutputStream; using (StreamWriter sw = new StreamWriter(output)) { sw.Write(responseBody); } Console.WriteLine("响应结束"); } catch (Exception err) { Console.WriteLine(err.Message); } } } catch (Exception err) { Console.WriteLine("程序异常,请重新打开程序:" + err.Message); } Console.Read(); }
// get --> bot asks for cmds to execute private void handleGET(Slave slave, HttpListenerRequest request, HttpListenerResponse response) { if (slave.noCmds()) { // check if slave has commands to execute response.AppendHeader("cookie", ""); } else { string cmd = slave.getcmd(); if (cmd.Contains(">")) { // if redirect string[] elements = cmd.Split(new Char[] { '>' }); slave.redirectFile = elements[1]; response.AppendHeader("cookie", elements[0]); } else { // send command from buffer response.AppendHeader("cookie", cmd); } } }
public static void servidor(object o) { var context = o as HttpListenerContext; //HttpListenerContext context = server.GetContext(); HttpListenerResponse response = context.Response; response.AppendHeader("Access-Control-Allow-Origin", "*"); response.AppendHeader("Access-Control-Allow-Methods", "POST, GET"); response.AppendHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); HttpListenerRequest request = context.Request; JArray c = new JArray(); string msg; if (request.HttpMethod == "POST") //Valido que sea un post { string line; //string donde guardo la linea StreamReader sr = new StreamReader(request.InputStream); //Leo un stream line = sr.ReadToEnd(); //Hasta que este al final de la linea (\0) PrintReceiptForTransaction(line); //Funcion que imprime } else if (request.HttpMethod == "GET") { foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters) { c.Add(printer); } } msg = c.ToString();//lo guardo en un string byte[] buffer = Encoding.UTF8.GetBytes(msg); response.ContentLength64 = buffer.Length; Stream st = response.OutputStream; st.Write(buffer, 0, buffer.Length); context.Response.Close(); }
private void Output(HttpListenerResponse response, int statusCode, string message) { //构造Response响应 response.StatusCode = 200; response.ContentType = "application/json;charset=UTF-8"; response.ContentEncoding = Encoding.UTF8; response.AppendHeader("Content-Type", "application/json;charset=UTF-8"); using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) { var result = new { result = statusCode, message = message }; writer.Write(JsonConvert.SerializeObject(result)); writer.Close(); } }
/// <summary> /// 启用gzip压缩 /// </summary> public static bool EnableGzip(this HttpListenerResponse response, HttpListenerRequest request, out string acceptEncoding) { acceptEncoding = request.Headers["Accept-Encoding"]; var isGzip = false; if (acceptEncoding.NotNullOrEmpty()) { isGzip = acceptEncoding.ToLower().Contains("gzip"); if (isGzip && response.Headers["Content-Encoding"].IsNullOrEmpty()) { response.AppendHeader("Content-Encoding", "gzip"); } } return(isGzip); }