/// <summary> /// Returns description of HttpStatusCodesEnum (using reflection) /// </summary> /// <param name="code"></param> /// <returns></returns> private static string GetHttpResponseCodeDescription(HttpStatusCodesEnum code) { var type = code.GetType(); // fetch public members of enum var memberInfo = type.GetMember(code.ToString()); if (memberInfo.Length <= 0) return code.ToString(); // fetch attributes from this public members var attributes = memberInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false); // get content of attribute return attributes.Length > 0 ? ((DescriptionAttribute) attributes[0]).Description : code.ToString(); }
/// <summary> /// Sends error response to client /// </summary> /// <param name="client"></param> /// <param name="code"></param> private static void SendError(TcpClient client, HttpStatusCodesEnum code) { var intCode = (int) code; var responseCode = $"{intCode} {GetHttpResponseCodeDescription(code)}\n"; var html = $"<html><body><h1>{responseCode}</h1></body></html>"; var clientResponse = Encoding.UTF8.GetBytes($"HTTP/1.1 {responseCode}Content-Type: text/html\nContent-Length:{html.Length}\n\n{html}"); client.GetStream().Write(clientResponse, 0, clientResponse.Length); client.Close(); }