public WebServerResponse generateResponse(WebServerRequest request) { System.Collections.Specialized.NameValueCollection extraHeaders = new System.Collections.Specialized.NameValueCollection(); //Session handling Dictionary <string, object> sessionData; if (request.Cookies["SESSID"] != null && sessionsData.ContainsKey(request.Cookies["SESSID"])) { sessionData = sessionsData[request.Cookies["SESSID"]]; } else { string sessionId = Guid.NewGuid().ToString("N"); extraHeaders.Add("Set-Cookie", String.Format("{0}={1}; Path=/", "SESSID", sessionId)); sessionData = new Dictionary <string, object>(); sessionsData[sessionId] = sessionData; } string path = request.Path.Trim(new char[] { ' ', '/' }); WebServerResponse response; if (path == "test") { response = new WebServerResponse(); //Calculate response body string responseBody = ""; responseBody += "<html><head>\r\n"; responseBody += "\r\n</head><body>\r\n"; responseBody += "<h1>Successfully Connected</h1>"; responseBody += "\r\n</body></html>"; response.BodyString = responseBody; } else if (path == "json" || path.StartsWith("json/")) { response = ServeJson(request, sessionData); } else { string filePath = Path.Combine(HtdocsPath.FullName, path.Replace('/', '\\')); response = ServeFile(filePath); } if (extraHeaders.Count > 0) { response.Headers.Add(extraHeaders); } return(response); }
protected WebServerResponse ServeJson(WebServerRequest request, Dictionary <string, object> sessionData) { string contentType = "application/json"; WebServerResponse response = new WebServerResponse(); string action = request.Path.Substring("/json".Length).ToLower().Trim(new char[] { '/' }); if (action.Length > 0 && action != "compound") { if (JSONCallHandlers.ContainsKey(action)) { string requestData = null; if (request.Data is string) { requestData = (string)request.Data; } response.BodyString = jsonSerializer.Serialize(JSONCallHandlers[action](requestData, sessionData)); } else { throw new HttpException(404, "Not Found"); } } else { Dictionary <string, string> postData; if (request.Data is Dictionary <string, string> ) { postData = (Dictionary <string, string>)request.Data; } else if (request.Data is Dictionary <string, object> ) { try { postData = ((Dictionary <string, object>)request.Data).ToDictionary(k => k.Key, k => !(k.Value is string) ? "" : (string)k.Value); } catch { throw new HttpException(400, "Bad Request"); } } else { throw new HttpException(400, "Bad Request"); } Dictionary <string, object> returnData = new Dictionary <string, object>(); foreach (KeyValuePair <string, string> pair in postData) { string key = pair.Key.ToLower(); try { if (JSONCallHandlers.ContainsKey(key)) { if (!(pair.Value is string)) { returnData.Add(key, new { Error = true, ErrorCode = 400, ErrorMessage = "Bad Request" }); continue; } returnData.Add(key, JSONCallHandlers[key](pair.Value, sessionData)); } else { returnData.Add(key, new { Error = true, ErrorCode = 404, ErrorMessage = "Not Found" }); } } catch (HttpException ex) { returnData.Add(key, new { Error = true, ErrorCode = ex.ErrorCode, ErrorMessage = ex.Message }); } catch { returnData.Add(key, new { Error = true, ErrorCode = 500, ErrorMessage = "Internal Server Error" }); } } response.BodyString = jsonSerializer.Serialize(returnData); } //Set the content type response.Headers.Add("Content-Type", contentType); return(response); }
protected void handleClient(TcpClient client) { NetworkStream stream = client.GetStream(); try { byte[] data = new byte[client.ReceiveBufferSize]; int numBytesRead = stream.Read(data, 0, client.ReceiveBufferSize); string requestString = new UTF8Encoding().GetString(data, 0, numBytesRead); CustomHttpRequest httpRequest = CustomHttpRequest.Parse(requestString); WebServerRequest webServerRequest = new WebServerRequest(); webServerRequest.Cookies = httpRequest.Cookies; webServerRequest.Body = httpRequest.Body; webServerRequest.Path = httpRequest.RequestTarget.LocalPath; //Parse additional data Dictionary <string, List <string> > queryParts = ParseQuery(httpRequest.RequestTarget.Query); object additionalData = null; if (httpRequest.Method == "POST") { if (httpRequest.PostData.ContainsKey(dataKey)) { additionalData = httpRequest.PostData[dataKey]; } else { additionalData = httpRequest.PostData; } } else { if (queryParts.ContainsKey(dataKey) && queryParts[dataKey].Count > 0) { additionalData = queryParts[dataKey].First(); } } webServerRequest.Data = additionalData; CustomHttpResponse response = new CustomHttpResponse(generateResponse(webServerRequest)); response.ToStream(stream); } catch (System.Web.HttpException ex) { new CustomHttpResponse(ex).ToStream(stream); } catch { if (client.Connected) { try { CustomHttpResponse response = new CustomHttpResponse(); response.StatusCode = "500 Internal Server Error"; response.ToStream(stream); } catch { } } } client.Close(); }
protected void handleRequest(Dictionary <string, object> request) { processRequestThreads.Add(System.Threading.Thread.CurrentThread); if (!request.ContainsKey(idKey) || !request.ContainsKey(pathKey)) { return; } int id = (int)request[idKey]; object responceObj = null; try { WebServerRequest webServerRequest = new WebServerRequest(); webServerRequest.Path = (string)request[pathKey]; if (request.ContainsKey(dataKey)) { if (request[dataKey] is string) { webServerRequest.Data = (string)request[dataKey]; } else if (request[dataKey] != null) { webServerRequest.Data = request[dataKey]; } } if (request.ContainsKey(cookiesKey) && request[cookiesKey] is Dictionary <string, object> ) { System.Collections.Specialized.NameValueCollection cookies = new System.Collections.Specialized.NameValueCollection(); foreach (KeyValuePair <string, object> cookie in (Dictionary <string, object>)request[cookiesKey]) { if (!(cookie.Value is string)) { continue; } cookies.Add(cookie.Key, (string)cookie.Value); } webServerRequest.Cookies = cookies; } WebServerResponse response = _webServer.generateResponse(webServerRequest); List <SerializableKeyValuePair <string, string> > headers = new List <SerializableKeyValuePair <string, string> >(); for (int i = 0; i < response.Headers.AllKeys.Length; i++) { string key = response.Headers.Keys[i]; foreach (string value in response.Headers.GetValues(i)) { headers.Add(new SerializableKeyValuePair <string, string>(key, value)); } } responceObj = new { id = id, status = response.StatusCode, body = response.BodyString, headers = headers }; } catch (HttpException ex) { responceObj = new { id = id, status = ex.GetHttpCode().ToString() + " " + ex.Message }; } catch { responceObj = new { id = id, status = "500 Internal Server Error" }; } reply(responceObj); processRequestThreads.Remove(System.Threading.Thread.CurrentThread); }