Exemplo n.º 1
0
        public HttpResponse
        (
            HttpResponseCode code,
            string contentType,
            Stream contentStream,
            bool keepAliveConnection,
            IEnumerable <KeyValuePair <string, string> > headers
        )
        {
            ContentStream = contentStream;

            CloseConnection = !keepAliveConnection;

            ResponseCode = code;
            Headers      = new ListHttpHeaders
                           (
                new[]
            {
                new KeyValuePair <string, string>("Date", DateTime.UtcNow.ToString("R")),
                new KeyValuePair <string, string>("Connection", CloseConnection ? "Close" : "Keep-Alive"),
                new KeyValuePair <string, string>("Content-Type", contentType),
                new KeyValuePair <string, string>
                    ("Content-Length", ContentStream.Length.ToString(CultureInfo.InvariantCulture))
            }.Concat(headers)
                .ToList()
                           );
        }
Exemplo n.º 2
0
 public HttpResponse(HttpResponseCode code, string contentType, Stream contentStream, bool keepAliveConnection) :
     this
     (
         code, contentType, contentStream, keepAliveConnection, Enumerable.Empty <KeyValuePair <string, string> >()
     )
 {
 }
        public void TestServerErrorParse()
        {
            HttpResponseCode parsedHttpCode = HttpResponseCode.Unknown;

            parsedHttpCode.TryParse(500, out parsedHttpCode);
            Assert.AreEqual(parsedHttpCode, HttpResponseCode.AllServerErrors);
        }
        public void TestSuccessParse()
        {
            HttpResponseCode parsedHttpCode = HttpResponseCode.Unknown;

            parsedHttpCode.TryParse(200, out parsedHttpCode);
            Assert.AreEqual(parsedHttpCode, HttpResponseCode.Success);
        }
Exemplo n.º 5
0
        public RespDataBase(HttpResponseCode code)
        {
            this.Code = ((int)code).ToString();
            var filed = code.GetType().GetField(code.ToString());

            this.Message = ((DescriptionAttribute)filed.GetCustomAttributes(typeof(DescriptionAttribute), true).First()).Description;
        }
 public static Task RespondStatus(this IHttpContext context, HttpResponseCode code, string message = null, bool keepAlive = true)
 => context.Respond(code == HttpResponseCode.NoContent
         ? (IHttpResponse)EmptyHttpResponse.Create(code, keepAlive)
         : StringHttpResponse.Text(
                        message != null
                 ? code + Environment.NewLine + Environment.NewLine + message
                 : code.ToString(),
                        code, keepAlive));
Exemplo n.º 7
0
 public static HttpResponse CreateWithMessage(HttpResponseCode code, string message, string body = "")
 {
     return(new HttpResponse(
                code,
                string.Format(
                    "<html><head><title>{0}</title></head><body><h1>{1}</h1><hr><b>{0}</b>{2}</body></html>",
                    HttpServer.Instance.Banner, message, body)));
 }
Exemplo n.º 8
0
 /// <summary>
 /// Get the message associated with the ResponseCode enum
 /// </summary>
 /// <param name="responseCode"></param>
 /// <returns></returns>
 public static string ResponseMessage(this HttpResponseCode responseCode, string alternate = null)
 {
     if (alternate != null)
     {
         return(alternate);
     }
     return(ResponseMessages[(int)responseCode]);
 }
        public FileResponse(HttpResponseCode responseCode, byte[] body, string mimeType)
            : base(ServerConfiguration.HttpVersion, responseCode)
        {
            this.AddHeader(new HttpHeader("Content-Type", mimeType));
            this.AddHeader(new HttpHeader("Content-Length", body.Length.ToString()));

            this.Body = body;
        }
Exemplo n.º 10
0
 public RedirectingHttpResponse(HttpResponseCode code, IStringLookup headers)
     : base(code, headers)
 {
     if ((int)code < 300 && (int)code > 399)
     {
         throw new ArgumentException("The response code must be a redirection code 3xx.", nameof(code));
     }
 }
        public ErrorResponse(HttpResponseCode responseCode, string errorText)
            : base(ServerConfiguration.HttpVersion, responseCode)
        {
            this.Body = ServerConfiguration.Encoding.GetBytes(errorText);

            this.AddHeader(new HttpHeader("Content-Type", MimeType));
            this.AddHeader(new HttpHeader("Content-Length", this.Body.Length.ToString()));
        }
Exemplo n.º 12
0
        public HttpResponse(HttpVersion httpVersion, HttpResponseCode responseCode)
        {
            this.HttpVersion  = httpVersion;
            this.ResponseCode = responseCode;

            this.headers = new List <HttpHeader>();
            this.cookies = new List <HttpCookie>();
        }
Exemplo n.º 13
0
 public static string GetDescription(this HttpResponseCode val)
 {
     DescriptionAttribute[] attributes = (DescriptionAttribute[])val
                                         .GetType()
                                         .GetField(val.ToString())
                                         .GetCustomAttributes(typeof(DescriptionAttribute), false);
     return(attributes.Length > 0 ? attributes[0].Description : string.Empty);
 }
Exemplo n.º 14
0
 public static HttpResponse CreateWithMessage(HttpResponseCode code, string message, bool keepAliveConnection, string body = "")
 {
     return new HttpResponse(
         code,
         string.Format(
             "<html><head><title>{0}</title></head><body><h1>{0}</h1><hr>{1}</body></html>",
             message, body), keepAliveConnection);
 }
 public static string ToReasonPhrase(this HttpResponseCode code)
 {
     if (reasonPhrases.TryGetValue(code, out string message))
     {
         return(message);
     }
     return("");
 }
Exemplo n.º 16
0
 public static HttpResponse CreateWithMessage(HttpResponseCode code, string message, bool keepAliveConnection, string body = "")
 {
     return(new HttpResponse(
                code,
                string.Format(
                    "<html><head><title>{0}</title></head><body><h1>{0}</h1><hr>{1}</body></html>",
                    message, body), keepAliveConnection));
 }
Exemplo n.º 17
0
        private HttpResponse(HttpContext context, HttpResponseCode code, string contentType, Stream contentStream)
        {
            Protocol        = "HTTP/1.1";
            ContentType     = contentType;
            CloseConnection = false;

            Code          = code;
            ContentStream = contentStream;
        }
Exemplo n.º 18
0
 public static IHttpResponse Create(Stream body, HttpResponseCode code = HttpResponseCode.Ok, string contentType = "text/html; charset=utf-8", bool keepAlive = true)
 {
     return(new StreamHttpResponse(body, code, new ListHttpHeaders(new[] {
         new KeyValuePair <string, string>("Date", DateTime.UtcNow.ToString("R")),
         new KeyValuePair <string, string>("content-type", contentType),
         new KeyValuePair <string, string>("connection", keepAlive ? "keep-alive" : "close"),
         new KeyValuePair <string, string>("content-length", body.Length.ToString(CultureInfo.InvariantCulture))
     })));
 }
Exemplo n.º 19
0
 public static IHttpResponse Create(HttpResponseCode code = HttpResponseCode.Ok, bool keepAlive = true)
 {
     return(new EmptyHttpResponse(code, new ListHttpHeaders(new[] {
         new KeyValuePair <string, string>("Date", DateTime.UtcNow.ToString("R")),
         new KeyValuePair <string, string>("content-type", "text/html"),
         new KeyValuePair <string, string>("connection", keepAlive ? "keep-alive" : "close"),
         new KeyValuePair <string, string>("content-length", "0")
     })));
 }
Exemplo n.º 20
0
 public Task<IHttpResponse> Provide(object value, HttpResponseCode responseCode = HttpResponseCode.Ok)
 {
     var memoryStream = new MemoryStream();
     var writer = new JsonTextWriter(new StreamWriter(memoryStream));
     var serializer = new JsonSerializer() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented};
     serializer.Serialize(writer, value);
     writer.Flush();
     return Task.FromResult<IHttpResponse>(new HttpResponse(responseCode, "application/json; charset=utf-8", memoryStream, true));
 }
Exemplo n.º 21
0
 public HttpResponse
 (
     HttpResponseCode code,
     string content,
     IEnumerable <KeyValuePair <string, string> > headers,
     bool closeConnection
 )
     : this(code, "text/html; charset=utf-8", StringToStream(content), closeConnection, headers)
 {
 }
        // Constructor to create a HTTP Response Message with code and body
        public HttpResponseMessage(HttpResponseCode code, string?body)
        {
            Version = "HTTP/1.1";
            Code    = code;
            Headers = new Dictionary <string, string>();
            Body    = body;

            // Initialize the headers
            _initHeaders();
        }
 //------------- CONSTRUCTORS -------------
 /// <summary>
 /// Initializes a new <see cref="HttpResponse"/> class.
 /// </summary>
 /// <param name="statusCode">Response Status Code</param>
 /// <param name="body">Response Body in byte[]</param>
 public HttpResponse(HttpResponseCode statusCode, byte[] body)
     : this()
 {
     this.StatusCode = statusCode;
     this.Body       = body;
     if (body?.Length > 0)
     {
         this.Headers.Add(new Header("Content-Length", body.Length.ToString()));
     }
 }
Exemplo n.º 24
0
 public static IHttpResponse Create(Stream body, HttpResponseCode code = HttpResponseCode.Ok, string contentType = "text/html; charset=utf-8", bool keepAlive = true)
 {
     return new StreamHttpResponse(body, code, new ListHttpHeaders(new[]
     {
         new KeyValuePair<string, string>("Date", DateTime.UtcNow.ToString("R")),
         new KeyValuePair<string, string>("content-type", contentType),
         new KeyValuePair<string, string>("connection", keepAlive ? "keep-alive" : "close"), 
         new KeyValuePair<string, string>("content-length", body.Length.ToString(CultureInfo.InvariantCulture)), 
     }));
 }
 public static StringHttpResponse Create(string body, string contentType,
                                         HttpResponseCode code = HttpResponseCode.OK,
                                         bool keepAlive        = true)
 {
     return(new StringHttpResponse(body, code, new ListStringLookup(new[] {
         new KeyValuePair <string, string>("Date", DateTime.UtcNow.ToString("R")),
         new KeyValuePair <string, string>("Content-Type", contentType),
         new KeyValuePair <string, string>("Connection", keepAlive ? "Keep-Alive" : "Close"),
         new KeyValuePair <string, string>("Content-Length", Encoding.UTF8.GetByteCount(body).ToString(CultureInfo.InvariantCulture))
     })));
 }
Exemplo n.º 26
0
        public HttpResponse(HttpResponseCode code, string contentType, Stream contentStream, bool keepAliveConnection)
        {
            Protocol = "HTTP/1.1";
            ContentType = contentType;
            
            Code = code;
            ContentStream = contentStream;
            _closeConnection = !keepAliveConnection;

            CacheHeaders(new StreamWriter(_headerStream));
        }
Exemplo n.º 27
0
        private HttpResponse(HttpResponseCode code, string contentType, Stream contentStream, bool keepAliveConnection)
        {
            Protocol = "HTTP/1.1";
            ContentType = contentType;
            
            Code = code;
            ContentStream = contentStream;
            _closeConnection = !keepAliveConnection;

            additionalHeaders = new List<KeyValuePair<string, string>>();
        }
Exemplo n.º 28
0
 public static EmptyHttpResponse Create(
     HttpResponseCode code = HttpResponseCode.OK,
     bool keepAlive        = true)
 {
     return(new EmptyHttpResponse(code, new ListStringLookup(new[] {
         new KeyValuePair <string, string>("Date", DateTime.UtcNow.ToString("R")),
         new KeyValuePair <string, string>("Content-Type", "text/html"),
         new KeyValuePair <string, string>("Connection", keepAlive ? "Keep-Alive" : "Close"),
         new KeyValuePair <string, string>("Content-Length", "0"),
     })));
 }
 public static void TryParse(this HttpResponseCode theEnum, int code, out HttpResponseCode result)
 {
     if (code >= 500 && code <= 599)
     {
         result = HttpResponseCode.AllServerErrors;
     }
     else
     {
         result = (HttpResponseCode)Enum.Parse(typeof(HttpResponseCode), code.ToString());
     }
 }
Exemplo n.º 30
0
        /// <summary>
        /// Creates a HTTP 1.1 header string to return to browsers
        /// </summary>
        /// <param name="status">Status Number ex. 200 for OK, 404 for file not found</param>
        /// <param name="contentType">content type of the response body</param>
        /// <param name="contentLength">length of response body</param>
        /// <returns>header string</returns>
        string CreateHeader(HttpResponseCode status, string contentType, int contentLength)
        {
            const string CRLF      = "\r\n";
            string       strHeader =
                "HTTP/1.1 " + ((int)status).ToString() + CRLF +
                "Server: " + Resources.ServerString + CRLF +
                "Content-Type: " + contentType + CRLF +
                "Accept-Ranges: bytes" + CRLF +
                "Content-Length: " + contentLength + CRLF + CRLF;

            return(strHeader);
        }
Exemplo n.º 31
0
 public HttpResponse(HttpResponseCode statusCode, byte[] body)
 {
     this.StatusCode = statusCode;
     this.Version    = HttpVersionType.HTTP11;
     this.Headers    = new List <Header>();
     this.Cookies    = new List <ResponseCookie>();
     this.Body       = body;
     if (body?.Length > 0)
     {
         this.Headers.Add(new Header("Content-Length", body.Length.ToString()));
     }
 }
Exemplo n.º 32
0
        public Task <IHttpResponse> Provide(object value, HttpResponseCode responseCode = HttpResponseCode.Ok)
        {
            var memoryStream = new MemoryStream();
            var writer       = new JsonTextWriter(new StreamWriter(memoryStream));
            var serializer   = new JsonSerializer {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented
            };

            serializer.Serialize(writer, value);
            writer.Flush();
            return(Task.FromResult <IHttpResponse>(new HttpResponse(responseCode, "application/json; charset=utf-8", memoryStream, true)));
        }
Exemplo n.º 33
0
        public HttpResponse(HttpResponseCode statusCode, byte[] body)
            : this()
        {
            this.Version = HttpVersionType.Http11;
            this.Code    = statusCode;
            this.Body    = body;

            if (body.Length > 0 && body != null)
            {
                this.Headers.Add(new Header("Content-Length", body.Length.ToString()));
            }
        }
Exemplo n.º 34
0
 public ConstStringHttpRequestHandler(string text,
                                      HttpResponseCode code = HttpResponseCode.OK,
                                      string contentType    = "text/html; charset=utf-8",
                                      bool keepALive        = true)
 {
     Text        = text;
     ContentType = contentType;
     Response    = StringHttpResponse.Create(text,
                                             contentType: contentType,
                                             code: code,
                                             keepAlive: keepALive);
 }
Exemplo n.º 35
0
 public ConstByteArrayHttpRequestHandler(byte[] content,
                                         HttpResponseCode code = HttpResponseCode.OK,
                                         string contentType    = "application/octet-stream",
                                         bool keepALive        = true)
 {
     Content     = content;
     ContentType = contentType;
     Response    = ByteArrayHttpResponse.Create(content, 0, content.Length,
                                                contentType: contentType,
                                                code: code,
                                                keepAlive: keepALive);
 }
Exemplo n.º 36
0
        public CompressedResponse(IHttpResponse child, MemoryStream memoryStream, string encoding)
        {
            _memoryStream = memoryStream;

            _responseCode = child.ResponseCode;
            _closeConnection = child.CloseConnection;
            _headers =
                new ListHttpHeaders(
                    child.Headers.Where(h => !h.Key.Equals("content-length", StringComparison.InvariantCultureIgnoreCase))
                        .Concat(new[]
                        {
                            new KeyValuePair<string, string>("content-length", memoryStream.Length.ToString(CultureInfo.InvariantCulture)),
                            new KeyValuePair<string, string>("content-encoding", encoding), 
                        })
                        .ToList());


        }
Exemplo n.º 37
0
        public HttpResponse(HttpResponseCode code, string contentType, Stream contentStream, bool keepAliveConnection, IEnumerable<KeyValuePair<string, string>> headers)
        {
            ContentStream = contentStream;

            _closeConnection = !keepAliveConnection;

            _responseCode = code;
            _headers = new ListHttpHeaders(new[]
            {
                new KeyValuePair<string, string>("Date", DateTime.UtcNow.ToString("R")),
                new KeyValuePair<string, string>("Connection", _closeConnection ? "Close" : "Keep-Alive"),
                new KeyValuePair<string, string>("Content-Type", contentType),
                new KeyValuePair<string, string>("Content-Length", ContentStream.Length.ToString(CultureInfo.InvariantCulture)),
            }.Concat(headers).ToList());

        }
Exemplo n.º 38
0
 public HttpResponse(HttpResponseCode code, string content, IEnumerable<KeyValuePair<string,string>> headers, bool closeConnection)
     : this(code, "text/html; charset=utf-8", StringToStream(content), closeConnection,headers)
 {
 }
Exemplo n.º 39
0
 public HttpResponse(HttpResponseCode code, string content, bool closeConnection)
     : this(code, "text/html; charset=utf-8", StringToStream(content), closeConnection)
 {
 }
Exemplo n.º 40
0
 public StringHttpResponse(string body, HttpResponseCode code, IHttpHeaders headers) : base(code, headers)
 {
     _body = body;
 }
Exemplo n.º 41
0
        public static IHttpResponse Create(string body, HttpResponseCode code = HttpResponseCode.Ok, string contentType = "text/html; charset=utf-8", bool keepAlive = true, IHttpHeaders headers = null)
        {
            // TODO : Add Overload
            if (headers == null)
            {
                headers = EmptyHttpHeaders.Empty;
            }

            return new StringHttpResponse(body, code, new CompositeHttpHeaders(new ListHttpHeaders(new[]
            {
                new KeyValuePair<string, string>("Date", DateTime.UtcNow.ToString("R")),
                new KeyValuePair<string, string>("content-type", contentType),
                new KeyValuePair<string, string>("connection", keepAlive ? "keep-alive" : "close"), 
                new KeyValuePair<string, string>("content-length", Encoding.UTF8.GetByteCount(body).ToString(CultureInfo.InvariantCulture)), 
            }), headers));
        }
Exemplo n.º 42
0
 protected HttpResponseBase(HttpResponseCode code, IHttpHeaders headers)
 {
     _code = code;
     _headers = headers;
 }
Exemplo n.º 43
0
 public HttpException(HttpResponseCode responseCode, string message)
     : base(message)
 {
     _responseCode = responseCode;
 }
Exemplo n.º 44
0
 public HttpException(HttpResponseCode responseCode)
 {
     _responseCode = responseCode;
 }
Exemplo n.º 45
0
        /// <summary>
        /// Sends an error response on the socket. Also closes the socket
        /// </summary>
        /// <param name="sock">socket to send response to</param>
        /// <param name="status">Error Code</param>
        /// <param name="errMessage">Message</param>
        void SendErrorResponse(ref Socket sock, HttpResponseCode status, string errMessage)
        {
            StreamReader reader;
            string strErrorPage;
            try
            {
                string strFilePath = Path.Combine(m_strWebRoot, "error.html");
                reader = new StreamReader(strFilePath, Encoding.UTF8);
                strErrorPage = reader.ReadToEnd();
                reader.Close(); reader = null;

                strErrorPage = strErrorPage.Replace("<$ErrorMessage$>", errMessage);
            }
            catch
            {
                strErrorPage = errMessage;
            }

            byte [] outbuf = Encoding.UTF8.GetBytes(strErrorPage);
            string strHeader = CreateHeader(status, "text/html;charset=utf-8", outbuf.Length);
            // Header is always in ASCII encoding
            try
            {
                sock.Send(Encoding.ASCII.GetBytes(strHeader));
                sock.Send(outbuf, outbuf.Length, SocketFlags.None);
            }
            catch { }
            sock.Shutdown(SocketShutdown.Both);
            sock.Close(); sock = null;
        }
Exemplo n.º 46
0
		/// <summary>
		/// Constructor with response code and optional message
		/// </summary>
		/// <param name="responseCode"></param>
		/// <param name="message"></param>
		public HttpException(HttpResponseCode responseCode, string message = null) : base(responseCode.ResponseMessage(message))
		{
			ResponseCode = responseCode;
		}
Exemplo n.º 47
0
		public HttpResponse(HttpResponseCode code, string contentType, string content, bool closeConnection)
				: this(code, contentType, StringToStream(content), closeConnection)
		{
		}
Exemplo n.º 48
0
 public HttpResponse(HttpResponseCode code, string contentType, Stream contentStream, bool keepAliveConnection) :
     this(code, contentType, contentStream, keepAliveConnection, Enumerable.Empty<KeyValuePair<string, string>>())
 {
 }
Exemplo n.º 49
0
 /// <summary>
 /// Creates a HTTP 1.1 header string to return to browsers
 /// </summary>
 /// <param name="status">Status Number ex. 200 for OK, 404 for file not found</param>
 /// <param name="contentType">content type of the response body</param>
 /// <param name="contentLength">length of response body</param>
 /// <returns>header string</returns>
 string CreateHeader(HttpResponseCode status, string contentType, int contentLength)
 {
     const string CRLF = "\r\n";
     string strHeader =
         "HTTP/1.1 " + ((int)status).ToString() + CRLF +
         "Server: " + Resources.ServerString + CRLF +
         "Content-Type: " + contentType + CRLF +
         "Accept-Ranges: bytes" + CRLF +
         "Content-Length: " + contentLength + CRLF + CRLF;
     return strHeader;
 }
Exemplo n.º 50
0
 public HttpResponse(HttpResponseCode code, byte[] contentStream, bool keepAliveConnection) 
     : this (code, "text/html; charset=utf-8", new MemoryStream(contentStream), keepAliveConnection)
 {
 }
Exemplo n.º 51
0
 public EmptyHttpResponse(HttpResponseCode code, IHttpHeaders headers) : base(code, headers)
 {
     
 }
Exemplo n.º 52
0
 public StreamHttpResponse(Stream body, HttpResponseCode code, IHttpHeaders headers) : base(code, headers)
 {
     _body = body;
 }
Exemplo n.º 53
0
 public static IHttpResponse Create(HttpResponseCode code = HttpResponseCode.Ok, bool keepAlive = true)
 {
     return new EmptyHttpResponse(code, new ListHttpHeaders(new[]
     {
         new KeyValuePair<string, string>("Date", DateTime.UtcNow.ToString("R")),
         new KeyValuePair<string, string>("content-type", "text/html"),
         new KeyValuePair<string, string>("connection", keepAlive ? "keep-alive" : "close"), 
         new KeyValuePair<string, string>("content-length", "0"), 
     }));
 }
Exemplo n.º 54
0
 public RenderResponse(HttpResponseCode code, object state)
 {
     _code = code;
     _state = state;
 }
Exemplo n.º 55
0
 public static Task<IControllerResponse> Render(HttpResponseCode code)
 {
     return Create(new RenderResponse(code, null));
 }