/// <summary> /// Automatically sends the appropriate response to the user agent. /// </summary> /// <param name="response">The response to set to this message.</param> public virtual void Send(HttpListenerResponse response) { Requires.NotNull(response, "response"); response.StatusCode = (int)this.Status; MessagingUtilities.ApplyHeadersToResponse(this.Headers, response); foreach (HttpCookie httpCookie in this.Cookies) { var cookie = new Cookie(httpCookie.Name, httpCookie.Value) { Expires = httpCookie.Expires, Path = httpCookie.Path, HttpOnly = httpCookie.HttpOnly, Secure = httpCookie.Secure, Domain = httpCookie.Domain, }; response.AppendCookie(cookie); } if (this.ResponseStream != null) { response.ContentLength64 = this.ResponseStream.Length; this.ResponseStream.CopyTo(response.OutputStream); } response.OutputStream.Close(); }
public static void SendTemplateResponse(HttpListenerResponse response, string cookieName, ConceptCard card) { // Looks like we need to write the card info in the template instead, and // provide a way for the later call to get access to it. response.AppendCookie(new Cookie(cookieName, card.id.ToString())); string returnFile = templateFile; if (card != null) { returnFile = SetRefresh(true, returnFile); returnFile = returnFile.Replace("__TEMPLATE_ITEM_1__", $"<IMG SRC = \"CustomCard_{card.id}.jpg\" ID=\"bg\">"); } else { returnFile = SetRefresh(false, returnFile); returnFile = returnFile.Replace("__TEMPLATE_ITEM_1__", "The draw pile is empty. Wait for another player to discard a card!"); } Console.WriteLine($"{DateTime.Now}:Sending template with for card:" + ((card != null) ? card.id.ToString() : "no_card")); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(returnFile); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); }
public static HttpListenerResponse Cookie(this HttpListenerResponse response, string name, string value, string path = null, string domain = null) { if (path == null) { response.AppendCookie(new Cookie(name, value)); } else if (domain == null) { response.AppendCookie(new Cookie(name, value, path)); } else { response.AppendCookie(new Cookie(name, value, path, domain)); } return(response); }
public override void AppendCookie(HttpCookie cookie) { _netResponse.AppendCookie(new Cookie { Name = cookie.Name, Value = cookie.Value, Path = cookie.Path, }); }
private void SetCookies(HttpListenerResponse resp) { if (_cookies == null) { return; } foreach (Cookie cookie in _cookies) { resp.AppendCookie(cookie); } }
public async Task AppendCookie_ValidCookie_AddsCookieToCollection() { HttpListenerResponse response = await GetResponse(); var cookie1 = new Cookie("name1", "value"); var cookie2 = new Cookie("name2", "value2"); response.AppendCookie(cookie1); response.AppendCookie(cookie2); Assert.Equal(new Cookie[] { cookie1, cookie2 }, response.Cookies.Cast <Cookie>()); var cookie3 = new Cookie("name1", "value2"); response.AppendCookie(cookie3); Assert.Equal(new Cookie[] { cookie3, cookie2 }, response.Cookies.Cast <Cookie>()); // Cookies are not cloned. cookie3.Value = "value3"; Assert.Equal("value3", response.Cookies[0].Value); }
public static void SimpleListenerCookieExample(string[] prefixes) { // Create a listener. HttpListener listener = new HttpListener(); // Add the prefixes. foreach (string s in prefixes) { listener.Prefixes.Add(s); } listener.IgnoreWriteExceptions = true; listener.Start(); Console.WriteLine("Listening..."); // Note: The GetContext method blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; string customerID = null; // Did the request come with a cookie? Cookie cookie = request.Cookies["ID"]; if (cookie != null) { customerID = cookie.Value; } if (customerID != null) { Console.WriteLine("Found the cookie!"); } // Get the response object. HttpListenerResponse response = context.Response; // If they didn't provide a cookie containing their ID, give them one. if (customerID == null) { customerID = NextCustomerID(); Cookie cook = new Cookie("ID", customerID); response.AppendCookie(cook); } // Construct a response. string responseString = "<HTML><BODY> Hello " + customerID + "!</BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); // Get the response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); // Closing the response sends the response to the client. response.Close(); listener.Stop(); }
public bool AppendCookie(Cookie cookie) { try { if (cookie == null) { return(false); } response.AppendCookie(cookie); return(true); } catch { return(false); } }
public static void SendTemplateResponse(HttpListenerResponse response, string cookieName, string text) { // Use this to provide text to the user, while still showing the buttons for action. Cookie deletedCookie = new Cookie(cookieName, "NO_CARD"); deletedCookie.Expires = DateTime.MinValue; response.AppendCookie(deletedCookie); string returnFile = templateFile; returnFile = SetRefresh(false, returnFile); returnFile = returnFile.Replace("__TEMPLATE_ITEM_1__", $"<DIV class=\"infotext\">{text}</DIV>"); Console.WriteLine($"{DateTime.Now}:Sending template with text:{text}"); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(returnFile); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); }
public async Task AppendCookie_NullCookie_ThrowsArgumentNullException() { HttpListenerResponse response = await GetResponse(); AssertExtensions.Throws <ArgumentNullException>("cookie", () => response.AppendCookie(null)); }
public void AppendCookie(Cookie cookie) => inner.AppendCookie(cookie);
public override void AppendCookie(HttpCookie cookie) { _response.AppendCookie(new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain)); }
/// <summary> /// Adds a Cookie /// </summary> /// <param name="cookie">The cookie to add</param> /// <returns> /// itself wit after the operation was performed /// </returns> public IServerResponse AddCookie(Cookie cookie) { _res.AppendCookie(cookie); return(this); }
void SetHeaders() { if (IsDataSent) { return; } if (StatusCode != null) { response.StatusCode = (int)StatusCode; } if (StatusMessage != null) { response.StatusDescription = StatusMessage; } if (Chunked != null) { response.SendChunked = (bool)Chunked; } if (Headers != null) { foreach (var header in Headers) { response.AppendHeader(header.Key, header.Value); } } if (Cookies != null) { foreach (var cookie in Cookies) { var cookieObj = new Cookie(cookie.Key, cookie.Value); if (CookiePath != null && CookiePath.ContainsKey(cookie.Key)) { cookieObj.Path = CookiePath[cookie.Key]; } if (CookieExpire != null && CookieExpire.ContainsKey(cookie.Key)) { cookieObj.Expires = DateTime.Now.AddSeconds(CookieExpire[cookie.Key]); } response.AppendCookie(cookieObj); } } if (ContentType != null) { response.ContentType = ContentType; } if (RedirectLocation != null) { if (StatusCode == null) { response.StatusCode = 302; } response.RedirectLocation = RedirectLocation; } if (AllowCors) { response.AppendHeader("Access-Control-Expose-Headers", String.Join(", ", response.Headers.AllKeys)); response.AppendHeader("Access-Control-Allow-Origin", "*"); } IsDataSent = true; }
// // Summary: // Adds the specified System.Net.Cookie to the collection of cookies for this response. // // Parameters: // cookie: // The System.Net.Cookie to add to the collection to be sent with this response // // Exceptions: // T:System.ArgumentNullException: // cookie is null. public void AppendCookie(Cookie cookie) { response.AppendCookie(cookie); }
/// <summary> /// Appends cookie to the response /// </summary> public void AppendCookie(Cookie cookie) { m_NetResponse.AppendCookie(cookie); }
/// <summary> /// 将指定的 System.Net.Cookie 添加到此响应的 Cookie 集合。 /// </summary> /// <param name="cookie"></param> public virtual void AppendCookie(Cookie cookie) { _response.AppendCookie(cookie); }
public void AppendCookie(Cookie cookie) { InnerResponse.AppendCookie(cookie); }
public void AppendCookie(System.Net.Cookie cookie) { Response.AppendCookie(cookie); }
/// <summary> /// 收到POST消息处理 /// </summary> /// <param name="request">request消息结构</param> /// <param name="response">response消息结构</param> public override void onPost(HttpListenerRequest request, HttpListenerResponse response) { Console.WriteLine("POST:" + request.Url); String ip = request.RemoteEndPoint.Address.ToString(); int port = request.RemoteEndPoint.Port; Log.WriteDebug("收到POST消息:IP=" + ip + ";Port=" + port); try { //空消息 if (!request.HasEntityBody) { Log.WriteDebug("收到POST消息,消息内容为空!"); if (request.Cookies.Count > 0) { foreach (Cookie cookie in request.Cookies) { response.AppendCookie(cookie); } } byte[] xml = RecvEmptyMsgHandle(ip, port); if (xml.Length <= 0) { response.ContentLength64 = 0; //回复空post Log.WriteDebug("收到POST消息,消息内容为空!回复空消息"); } else { response.OutputStream.Write(xml, 0, xml.Length); Log.WriteDebug("收到POST消息,消息内容为空!回复消息:\n" + System.Text.Encoding.Default.GetString(xml)); } //MessageBox.Show("yyyy:" + ip + ":" + port + " " + getSnForSnIpPortNode(ip,port)); } else { //接收POST参数 Stream stream = request.InputStream; System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8); //String body = reader.ReadToEnd(); XmlParameterStruct parameterStruct = new XmlParameterStruct(); string msg = reader.ReadToEnd(); Log.WriteDebug("收到AP消息。消息内容:\n" + msg); parameterStruct = new XmlHandle().HandleRecvApMsg(msg); Log.WriteDebug(string.Format("收到[{0}]POST消息,消息Method={1}!", parameterStruct.xmlInform.SN, parameterStruct.Method)); if (request.Cookies.Count > 0) { foreach (Cookie cookie in request.Cookies) { response.AppendCookie(cookie); } } else { Random rand = new Random(DateTime.Now.Millisecond); Cookie cookie = new Cookie("JSESSIONID", string.Format("{0}{1}{2}{3}", rand.Next().ToString(), rand.Next().ToString(), rand.Next().ToString(), rand.Next().ToString())); cookie.Path = "/"; response.AppendCookie(cookie); //response.AppendCookie(new Cookie("sn", parameterStruct.xmlInform.SN)); } if (String.Compare(parameterStruct.Method, RPCMethod.Inform, true) == 0) { ApConnHmsInfo connInfo = new ApConnHmsInfo(parameterStruct.xmlInform.SN); connInfo.Ip = request.RemoteEndPoint.Address.ToString(); connInfo.Port = request.RemoteEndPoint.Port; connInfo.EventCode = parameterStruct.xmlInform.EventCode; Log.WriteDebug("收到Inform消息,SN = " + connInfo.Sn); if (!string.IsNullOrEmpty(connInfo.Sn)) { if (myDB.deviceinfo_record_exist(connInfo.Sn) != 1) { Log.WriteError(string.Format("设备({0})未开户,不回复消息。", connInfo.Sn)); return; } } else { Log.WriteError("未读到设备SN号。"); return; } foreach (string eventcode in connInfo.EventCode) { if (string.IsNullOrEmpty(eventcode)) { break; } Log.WriteDebug("消息EventCode = " + eventcode); } GlobalParameter.apConnHmsList.add(connInfo); Log.WriteDebug("设置" + parameterStruct.xmlInform.SN + "为上线状态!"); if (!myDB.SetconnHSToOnLine(parameterStruct.xmlInform.SN)) { Log.WriteError("设置" + parameterStruct.xmlInform.SN + "为上线状态失败!"); } if (XmlHandle.GetEventInList(connInfo.EventCode, InformEventCode.BOOT)) { Log.WriteDebug("设置AP(" + parameterStruct.xmlInform.SN + ")的告警为历史告警。"); int ret = myDB.alarminfo_record_set_2_history(parameterStruct.xmlInform.SN); if (ret != 0) { Log.WriteError(string.Format("更新AP的告警为历史告警出错,出错原因:({0}){1}。" , ret, myDB.get_rtv_str(ret))); } Log.WriteDebug("更新AP(" + parameterStruct.xmlInform.SN + ")反向连接地址为:" + parameterStruct.xmlInform.ConnectionRequestURL); int re = myDB.apconninfo_record_update(parameterStruct.xmlInform.SN, parameterStruct.xmlInform.ConnectionRequestURL, GlobalParameter.ConnectionRequestUsername, GlobalParameter.ConnectionRequestPassWd); if (re != 0) { Log.WriteError(string.Format("更新AP反向连接地址出错,出错原因:({0}){1}。" , ret, myDB.get_rtv_str(ret))); } Log.WriteDebug("更新AP(" + parameterStruct.xmlInform.SN + ")的IP地址为:" + connInfo.Ip); strDevice deviceInfo = new strDevice(); deviceInfo.ipAddr = connInfo.Ip; int errCode = myDB.deviceinfo_record_update(parameterStruct.xmlInform.SN, deviceInfo); if (0 != errCode) { Log.WriteError(string.Format("更新AP的IP地址出错,出错原因:({0}){1}。" , errCode, myDB.get_rtv_str(errCode))); } } if (XmlHandle.GetEventInList(connInfo.EventCode, InformEventCode.M_Reboot)) { string str = String.Format("修改SN({0}),任务类型({1}),任务状态({2})!", connInfo.Sn, TaskType.RebootTask, TaskStatus.ReponseOk); Log.WriteDebug(str); if (!myDB.SetApTaskStatusBySN(connInfo.Sn, TaskType.RebootTask, TaskStatus.ReponseOk)) { Log.WriteError(str); } } if (XmlHandle.GetEventInList(connInfo.EventCode, InformEventCode.VALUE_CHANGE)) { ChangeApDeviceInfo(parameterStruct); } //if (XmlHandle.GetEventInList(connInfo.EventCode, InformEventCode.PERIODIC)) //{ // CheckParameterList(connInfo.Sn, parameterStruct.parameterNode); //} byte[] res = XmlHandle.CreateInformResponseXmlFile();// Encoding.UTF8.GetBytes("OK"); response.OutputStream.Write(res, 0, res.Length); Log.WriteDebug("收到Inform消息,回复消息:\n" + System.Text.Encoding.Default.GetString(res)); } else { ApConnHmsInfo connInfo = GlobalParameter.apConnHmsList.getSnForconnList(ip, port); if (connInfo != null) { if (!string.IsNullOrEmpty(connInfo.Sn)) { if (myDB.deviceinfo_record_exist(connInfo.Sn) != 1) { Log.WriteError(string.Format("设备({0})未开户,不回复消息。", connInfo.Sn)); return; } } else { Log.WriteError("未读到设备SN号。"); return; } if (String.Compare(parameterStruct.Method, RPCMethod.GetParameterValuesResponse, true) == 0) { //去掉周期性查询 if (String.Compare(parameterStruct.ID, PeriodicGetValue, true) != 0) { string str = String.Format("修改SN({0}),任务ID({1}),任务状态({2})!", connInfo.Sn, parameterStruct.ID, TaskStatus.ReponseOk); Log.WriteDebug(str); if (!myDB.SetStatusBySnId(parameterStruct.ID, connInfo.Sn, TaskStatus.ReponseOk)) { Log.WriteError(str); } } Log.WriteDebug("更改数据库中AP的状态或参数值..."); CheckParameterList(connInfo.Sn, parameterStruct.parameterNode); SaveParameterList(connInfo.Sn, parameterStruct.ID, parameterStruct.parameterNode); } else if (String.Compare(parameterStruct.Method, RPCMethod.SetParameterValuesResponse, true) == 0) { //去掉1Boot的回复。 if (String.Compare(parameterStruct.ID, XmlHandle.SetParameterValueFor1Boot, true) != 0) { string str = String.Format("修改SN({0}),任务ID({1}),任务状态({2})!", connInfo.Sn, parameterStruct.ID, TaskStatus.ReponseOk); Log.WriteDebug(str); if (!myDB.SetStatusBySnId(parameterStruct.ID, connInfo.Sn, TaskStatus.ReponseOk)) { Log.WriteError(str); } //周期日志上传回复,保存Key string taskType = parameterStruct.ID.Substring(0, TaskType.GetLogTask.ToString().Length); if (taskType.Equals(TaskType.GetLogTask.ToString())) { if (GlobalParameter.AutonomousTransferKey.ContainsKey(connInfo.Sn)) { GlobalParameter.AutonomousTransferKey.Remove(connInfo.Sn); } GlobalParameter.AutonomousTransferKey.Add(connInfo.Sn, parameterStruct.ID); } } } else if (String.Compare(parameterStruct.Method, RPCMethod.TransferComplete, true) == 0) { TaskStatus status = TaskStatus.TaskNull; if (parameterStruct.transferComplete.FaultCode == 0) //AP返回成功 { status = TaskStatus.ReponseOk; //设置LOG上传成功标志 string taskType = parameterStruct.transferComplete.CommandKey.Substring(0, TaskType.GetLogTask.ToString().Length); if (taskType.Equals(TaskType.GetLogTask.ToString())) { string tmpstr = String.Format("修改SN({0}),任务ID({1}),AP LOG表状态为可用!", connInfo.Sn, parameterStruct.transferComplete.CommandKey); Log.WriteDebug(tmpstr); if (0 != myDB.aploginfo_record_update( connInfo.Sn, parameterStruct.transferComplete.CommandKey, 1)) { Log.WriteError(tmpstr); } } } else { status = TaskStatus.ReponseFail; } string str = String.Format("修改SN({0}),任务ID({1}),任务状态({2})!", connInfo.Sn, parameterStruct.transferComplete.CommandKey, status); Log.WriteDebug(str); if (!myDB.SetStatusBySnId(parameterStruct.transferComplete.CommandKey, connInfo.Sn, status)) { Log.WriteError(str); } byte[] res = XmlHandle.CreateTransferCompleteResponseXmlFile();// Encoding.UTF8.GetBytes("OK"); response.OutputStream.Write(res, 0, res.Length); Log.WriteDebug("收到TransferComplete消息,回复消息:\n" + System.Text.Encoding.Default.GetString(res)); return; } else if (String.Compare(parameterStruct.Method, RPCMethod.AutonomousTransferComplete, true) == 0) { string CommandKey = ""; if (String.IsNullOrEmpty(parameterStruct.autoTransferComplete.CommandKey)) { if (GlobalParameter.AutonomousTransferKey.ContainsKey(connInfo.Sn)) { CommandKey = GlobalParameter.AutonomousTransferKey[connInfo.Sn]; } } if (!string.IsNullOrEmpty(CommandKey) && parameterStruct.autoTransferComplete.FaultCode == 0) //AP返回成功 { //设置LOG上传成功标志 string taskType = CommandKey.Substring(0, TaskType.GetLogTask.ToString().Length); if (taskType.Equals(TaskType.GetLogTask.ToString())) { int ret = 0; string tmpstr = String.Format("修改SN({0}),任务ID({1}),AP LOG表状态为可用!", connInfo.Sn, CommandKey); Log.WriteDebug(tmpstr); //周期上传时,只保存最后一次的log if (1 == myDB.aploginfo_record_exist(connInfo.Sn, CommandKey)) { ret = myDB.aploginfo_record_delete(connInfo.Sn, CommandKey); if (0 != ret) { Log.WriteError(tmpstr + "出错。无法删除已有记录。错误原因:" + myDB.get_rtv_str(ret)); } } if (ret == 0) { ret = myDB.aploginfo_record_insert( connInfo.Sn, CommandKey, DateTime.Now.ToString(), parameterStruct.autoTransferComplete.TargetFileName, Convert.ToUInt32(parameterStruct.autoTransferComplete.FileSize), "None"); if (0 != ret) { Log.WriteError(tmpstr + "出错。错误原因:" + myDB.get_rtv_str(ret)); } else { ret = myDB.aploginfo_record_update(connInfo.Sn, CommandKey, 1); if (0 != ret) { Log.WriteError(tmpstr + "出错。错误原因:" + myDB.get_rtv_str(ret)); } } } } } byte[] res = XmlHandle.CreateAutonomousTransferCompleteResponseXmlFile();// Encoding.UTF8.GetBytes("OK"); response.OutputStream.Write(res, 0, res.Length); Log.WriteDebug("收到AutonomousTransferComplete消息,回复消息:\n" + System.Text.Encoding.Default.GetString(res)); return; } else if (String.Compare(parameterStruct.Method, RPCMethod.RebootResponse, true) == 0) { string str = String.Format("修改SN({0}),任务ID({1}),任务状态({2})!", connInfo.Sn, parameterStruct.ID, TaskStatus.SendTask); Log.WriteDebug(str); if (!myDB.SetStatusBySnId(parameterStruct.ID, connInfo.Sn, TaskStatus.SendTask)) { Log.WriteError(str); } } else if (String.Compare(parameterStruct.Method, RPCMethod.Fault, true) == 0) { string str = String.Format("修改SN({0}),任务ID({1}),任务状态({2})!", connInfo.Sn, parameterStruct.ID, TaskStatus.ReponseFail); Log.WriteDebug(str); if (!myDB.SetStatusBySnId(parameterStruct.ID, connInfo.Sn, TaskStatus.ReponseFail)) { Log.WriteError(str); } } } //如果有其它任务,下发其它任务,否则回复空 byte[] xml = NextSendMsgHandle(ip, port); if (xml.Length <= 0) { response.ContentLength64 = 0; //回复空post } else { response.OutputStream.Write(xml, 0, xml.Length); } } } } catch (Exception e) { Log.WriteError("处理收到的消息(" + ip + ":" + port + ")出错。"); Log.WriteError("出错原因:" + e.Message.ToString()); } }
/// <summary> /// Обработка пользовательского запроса в отдельном потоке. /// </summary> /// <param name="context">Контекст запроса</param> private void ProcessRequest(object context) { HttpListenerContext ctx = (HttpListenerContext)context; HttpListenerRequest request = ctx.Request; HttpListenerResponse response = ctx.Response; RequestContext rc = ParseRequest(request); // вначале проверяется не является ли запрошенный ресурс URL в таблице переходов if (this.routeTable.ContainsKey(rc.Route) && (request.Headers["Accept"].Contains("text/html") || request.Headers["Accept"].Contains("*/*"))) { // если да - запускаем парсер и возвращаем его ответ ResponseContext userResponse = ProcessRoute(rc); if (userResponse.redirectUrl != "") { // пользовательская функция вызвала метод перенаправления (redirect) if (rc.session != null) { response.AppendCookie(new Cookie("SSID", rc.session.sessionId)); } else { if (request.Cookies["SSID"] != null) { // удалить сессионные cookie response.AppendCookie(request.Cookies["SSID"]); response.Cookies["SSID"].Expired = true; response.Cookies["SSID"].Discard = true; } } response.Redirect(userResponse.redirectUrl); response.OutputStream.Close(); } else { // вернем в браузер ответ пользовательской функции // установим или удалим сессионные cookie if (rc.session != null) { response.AppendCookie(new Cookie("SSID", rc.session.sessionId)); } else { if (request.Cookies["SSID"] != null) { // удалить сессионные cookie response.AppendCookie(request.Cookies["SSID"]); response.Cookies["SSID"].Expired = true; response.Cookies["SSID"].Discard = true; } } byte[] buffer = System.Text.Encoding.GetEncoding(this.responseCodePage).GetBytes(userResponse.responseString); response.StatusCode = (int)userResponse.exitCode; response.ContentType = "text/html"; response.ContentLength64 = buffer.Length; Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } } else { // --- запрошенный ресурс не в таблице маршрутизации - это или ресурс или ошибочная ссылка if (!this.useEmbeddedResources) { // если сервер использует режим хранения ресурсов в файловой системе // получим имя запрашиваемого файла с защитой от доступа к ресурсам вне разрешенной папки string file = rc.Route.Replace("..\\", string.Empty).Replace("../", string.Empty).TrimStart('\\', '/'); string filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), this.staticContent, file); string extension = Path.GetExtension(filename); // проверим что запрашиваемый ресурс в списке разрешенных if (allowedMimeTypes.Keys.Contains(extension)) { if (File.Exists(filename)) { // ищем файл на сервере в доступных для этого папках и передаем Stream input = new FileStream(filename, FileMode.Open); response.ContentType = allowedMimeTypes[extension]; response.ContentLength64 = input.Length; this.CopyStream(input, response.OutputStream); input.Close(); response.OutputStream.Close(); } else { // файл не найден response.StatusCode = (int)HttpStatusCode.NotFound; response.ContentLength64 = 0; response.OutputStream.Close(); } } else { // запрошен неразрешенный тип файла response.StatusCode = (int)HttpStatusCode.Forbidden; response.ContentLength64 = 0; response.OutputStream.Close(); } } else { // если сервер использует режим хранения ресурсов в сборке EXE string embeddedResourceName = $"{Assembly.GetExecutingAssembly().GetName().Name}.Resources.{rc.Route.TrimStart('\\', '/')}"; string extension = Path.GetExtension(rc.Route); // проверим что запрашиваемый ресурс в списке разрешенных if (allowedMimeTypes.Keys.Contains(extension)) { // ищем запрошенный файл в ресурсах и передаем if ((Assembly.GetExecutingAssembly().GetManifestResourceNames().Where(x => x == embeddedResourceName).Count() > 0)) { Stream input = Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResourceName); response.ContentType = allowedMimeTypes[extension]; response.ContentLength64 = input.Length; this.CopyStream(input, response.OutputStream); input.Close(); response.OutputStream.Close(); } else { // файл не найден response.StatusCode = (int)HttpStatusCode.NotFound; response.ContentLength64 = 0; response.OutputStream.Close(); } } else { // запрошен неразрешенный тип файла response.StatusCode = (int)HttpStatusCode.Forbidden; // вначале всегда код возврата response.ContentLength64 = 0; response.OutputStream.Close(); // а в самом конце закрытие потока } } } }