Exemplo n.º 1
0
 protected override void DoSetHeaders()
 {
     base.DoSetHeaders();
     if (Server != "")
     {
         _RawHeaders.Values("Server", Server);
     }
     if (ContentType != "")
     {
         _RawHeaders.Values("Content-Type", ContentType);
     }
     if (Location != "")
     {
         _RawHeaders.Values("Location", Location);
     }
     if (ContentLength > -1)
     {
         _RawHeaders.Values("Content-Length", ContentLength.ToString());
     }
     if (LastModified.Ticks > 0)
     {
         _RawHeaders.Values("Last-Modified", Http.DateTimeGmtToHttpStr(LastModified));
     }
     if (AuthRealm != "")
     {
         ResponseNo = 401;
         _RawHeaders.Values("WWW-Authenticate", "Basic realm=\"" + AuthRealm + "\"");
         _ContentText = "<HTML><BODY><B>" + ResponseNo + " " + ResourceStrings.Unauthorized + "</B></BODY></HTML>";
     }
 }
Exemplo n.º 2
0
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.Clear();

            if (!String.IsNullOrEmpty(FileDownloadName))
            {
                context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=\"" + this.FileDownloadName + "\"");
            }

            if (!String.IsNullOrEmpty(ContentType))
            {
                context.HttpContext.Response.ContentType = ContentType;
            }

            if (ContentLength > 0)
            {
                context.HttpContext.Response.AddHeader("content-length", ContentLength.ToString());
            }

            if (Content != null && Content.Length > 0)
            {
                context.HttpContext.Response.BinaryWrite(Content);
            }

            if (!String.IsNullOrEmpty(VirtualPath))
            {
                context.HttpContext.Response.TransmitFile(VirtualPath);
            }

            context.HttpContext.Response.End();
        }
Exemplo n.º 3
0
        public override String ToString()
        {
            var result = new StringBuilder();

            result.AppendLine(HttpStatusCodeToString(HttpStatusCode));

            AddToResponseString(result, "Cache-Control", CacheControl);
            AddToResponseString(result, "Content-length", ContentLength.ToString());
            AddToResponseString(result, "content-type", ContentType.ToString());
            AddToResponseString(result, "Date", DateTime.Now.ToString());
            AddToResponseString(result, "Server", ServerName);
            if (KeepAlive)
            {
                AddToResponseString(result, "Connection", "Keep-Alive");
            }

            foreach (var key in Headers.AllKeys)
            {
                AddToResponseString(result, key, Headers[key]);
            }

            result.AppendLine();

            return(result.ToString());
        }
Exemplo n.º 4
0
        private string BuildHttpRequestMessage()
        {
            var message = new StringBuilder();

            message.AppendFormat("{0} {1} HTTP/1.1{2}", Method, RequestUri.PathAndQuery, HttpControlChars.CRLF);

            var messageHeaders = new WebHeaderCollection
            {
                [HttpRequestHeader.Host]           = RequestUri.Host,
                [HttpRequestHeader.Connection]     = "Close",
                [HttpRequestHeader.AcceptEncoding] = "gzip, deflate"
            };

            // Add content type information
            if (!string.IsNullOrEmpty(ContentType))
            {
                messageHeaders[HttpRequestHeader.ContentType] = ContentType;
            }

            // Add content length information
            if (ContentLength > 0)
            {
                messageHeaders[HttpRequestHeader.ContentLength] = ContentLength.ToString();
            }

            // Add the headers
            foreach (string key in Headers.Keys)
            {
                messageHeaders.Add(key, Headers[key]);
            }

            foreach (string key in messageHeaders)
            {
                message.AppendFormat("{0}: {1}{2}", key, messageHeaders[key], HttpControlChars.CRLF);
            }

            Headers = messageHeaders;

            // Add a blank line to indicate the end of the headers
            message.Append(HttpControlChars.CRLF);

            // No content to add
            if (_requestContentBuffer == null || _requestContentBuffer.Length <= 0)
            {
                return(message.ToString());
            }

            // Add content by reading data back from the content buffer
            using (var stream = new MemoryStream(_requestContentBuffer, false))
            {
                using (var reader = new StreamReader(stream))
                {
                    message.Append(reader.ReadToEnd());
                }
            }

            return(message.ToString());
        }
Exemplo n.º 5
0
        public string ResponseToString()
        {
            string response = "";

            response += HttpVersion + " " + StatusCode + " " + StatusString + "\n";
            response += "Via: Florian Weiss SWE1-MTCG-Server\n";
            response += "Content-type: " + ContentType + "\n";
            response += "Content-length: " + ContentLength.ToString() + "\n\n";
            response += Content;

            return(response);
        }
Exemplo n.º 6
0
 internal void Apply(HttpRequestMessageProperty hp)
 {
     if (Headers != null)
     {
         foreach (var key in Headers.AllKeys)
         {
             hp.Headers [key] = Headers [key];
         }
     }
     if (Accept != null)
     {
         hp.Headers ["Accept"] = Accept;
     }
     if (ContentLength > 0)
     {
         hp.Headers ["Content-Length"] = ContentLength.ToString(NumberFormatInfo.InvariantInfo);
     }
     if (ContentType != null)
     {
         hp.Headers ["Content-Type"] = ContentType;
     }
     if (IfMatch != null)
     {
         hp.Headers ["If-Match"] = IfMatch;
     }
     if (IfModifiedSince != null)
     {
         hp.Headers ["If-Modified-Since"] = IfModifiedSince;
     }
     if (IfNoneMatch != null)
     {
         hp.Headers ["If-None-Match"] = IfNoneMatch;
     }
     if (IfUnmodifiedSince != null)
     {
         hp.Headers ["If-Unmodified-Since"] = IfUnmodifiedSince;
     }
     if (Method != null)
     {
         hp.Method = Method;
     }
     if (SuppressEntityBody)
     {
         hp.SuppressEntityBody = true;
     }
     if (UserAgent != null)
     {
         hp.Headers ["User-Agent"] = UserAgent;
     }
 }
Exemplo n.º 7
0
        private void BuildServerVariables(HttpClient client)
        {
            ServerVariables = new NameValueCollection();

            // Add all headers.

            var allHttp = new StringBuilder();
            var allRaw  = new StringBuilder();

            foreach (var item in client.Headers)
            {
                ServerVariables[item.Key] = item.Value;

                string httpKey = "HTTP_" + (item.Key.Replace('-', '_')).ToUpperInvariant();

                ServerVariables[httpKey] = item.Value;

                allHttp.Append(httpKey);
                allHttp.Append('=');
                allHttp.Append(item.Value);
                allHttp.Append("\r\n");

                allRaw.Append(item.Key);
                allRaw.Append('=');
                allRaw.Append(item.Value);
                allRaw.Append("\r\n");
            }

            ServerVariables["ALL_HTTP"] = allHttp.ToString();
            ServerVariables["ALL_RAW"]  = allRaw.ToString();

            ServerVariables["CONTENT_LENGTH"] = ContentLength.ToString(CultureInfo.InvariantCulture);
            ServerVariables["CONTENT_TYPE"]   = ContentType;

            ServerVariables["LOCAL_ADDR"] = client.Server.EndPoint.Address.ToString();
            ServerVariables["PATH_INFO"]  = Path;

            string[] parts = client.Request.Split(new[] { '?' }, 2);

            ServerVariables["QUERY_STRING"]    = parts.Length == 2 ? parts[1] : "";
            ServerVariables["REMOTE_ADDR"]     = UserHostAddress;
            ServerVariables["REMOTE_HOST"]     = UserHostName;
            ServerVariables["REMOTE_PORT"]     = null;
            ServerVariables["REQUEST_METHOD"]  = RequestType;
            ServerVariables["SCRIPT_NAME"]     = Path;
            ServerVariables["SERVER_NAME"]     = client.Server.ServerUtility.MachineName;
            ServerVariables["SERVER_PORT"]     = client.Server.EndPoint.Port.ToString(CultureInfo.InvariantCulture);
            ServerVariables["SERVER_PROTOCOL"] = client.Protocol;
            ServerVariables["URL"]             = Path;
        }
Exemplo n.º 8
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Via.ToString());
            sb.Append(From.ToString());
            sb.Append($"To: <sip:{To.ToString()}>").AppendLine();
            sb.Append(CallId.ToString());
            sb.Append(CSeq.ToString());
            if (!string.IsNullOrEmpty(UserAgent))
            {
                sb.Append($"User-Agent: {UserAgent}").AppendLine();
            }
            if (Expires > 0)
            {
                sb.Append($"Expires: {Expires.ToString()}").AppendLine();
            }
            if (!string.IsNullOrEmpty(Accept))
            {
                sb.Append($"Accept: {Accept}").AppendLine();
            }
            if (!string.IsNullOrEmpty(ContentType))
            {
                sb.Append($"Content-Type: {ContentType}").AppendLine();
            }
            if (ContentLength > 0)
            {
                sb.Append($"Content-Length: {ContentLength.ToString()}").AppendLine();
            }
            sb.Append($"Max-Forwards: {MaxForwards}").AppendLine();
            if (Allow != null && Allow.Count > 0)
            {
                sb.Append($"Allow: {string.Join(",",Allow)}").AppendLine();
            }
            if (CustomHeaders.Count() > 0)
            {
                foreach (KeyValuePair <string, string> Header in CustomHeaders)
                {
                    sb.Append($"X-{Header.Key}: {Header.Value}").AppendLine();
                }
            }

            return(sb.ToString());
        }
Exemplo n.º 9
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("URI:" + uri.AbsoluteUri);
            if (Cookies != null)
            {
                foreach (HttpCookie cookie in Cookies)
                {
                    sb.AppendLine("Cookie:" + cookie.Name + ":" + cookie.Value);
                }
            }
            sb.AppendLine("Gzip:" + Gzip.ToString());
            sb.AppendLine("Method:" + Method);
            sb.AppendLine("ContentLength:" + ContentLength.ToString());
            sb.AppendLine("KeepAlive:" + KeepAlive.ToString());
            sb.AppendLine();
            sb.AppendLine(Data);
            return(sb.ToString());
        }
Exemplo n.º 10
0
        /// <summary>
        /// Produce a byte array containing only the headers.
        /// </summary>
        /// <returns>Byte array.</returns>
        public byte[] ToHeaderBytes()
        {
            string header = "";

            if (!String.IsNullOrEmpty(Id))
            {
                header += "Id: " + Id + Environment.NewLine;
            }
            header += "SyncRequest: " + SyncRequest + Environment.NewLine;
            header += "SyncResponse: " + SyncResponse + Environment.NewLine;
            header += "TimeoutMs: " + TimeoutMs.ToString() + Environment.NewLine;
            header += "SourceIp: " + SourceIp + Environment.NewLine;
            header += "SourcePort: " + SourcePort.ToString() + Environment.NewLine;
            header += "DestinationIp: " + DestinationIp + Environment.NewLine;
            header += "Type: " + Type.ToString() + Environment.NewLine;
            header += "ContentLength: " + ContentLength.ToString() + Environment.NewLine;
            header += Environment.NewLine;

            return(Encoding.UTF8.GetBytes(header));
        }
Exemplo n.º 11
0
        internal byte[] ToHeaderBytes()
        {
            string header = "";

            if (!String.IsNullOrEmpty(Id))
            {
                header += "Id: " + Id + Environment.NewLine;
            }
            header += "IsBroadcast: " + IsBroadcast + Environment.NewLine;
            header += "SyncRequest: " + SyncRequest + Environment.NewLine;
            header += "SyncResponse: " + SyncResponse + Environment.NewLine;
            header += "TimeoutMs: " + TimeoutMs.ToString() + Environment.NewLine;
            header += "SourceIpPort: " + SourceIpPort + Environment.NewLine;
            header += "DestinationIpPort: " + DestinationIpPort + Environment.NewLine;
            header += "Type: " + Type.ToString() + Environment.NewLine;
            header += "Metadata: " + Common.SerializeJson(Metadata, false) + Environment.NewLine;
            header += "ContentLength: " + ContentLength.ToString() + Environment.NewLine;
            header += Environment.NewLine;

            return(Encoding.UTF8.GetBytes(header));
        }
        public string this[string propertyName]
        {
            get
            {
                if (propertyName == "Accept")
                {
                    return(Accept);
                }
                else if (propertyName == "Accept-Charset")
                {
                    return(AcceptCharset);
                }
                else if (propertyName == "Accept-Encoding")
                {
                    return(AcceptEncoding);
                }
                else if (propertyName == "Accept-Language")
                {
                    return(AcceptLanguage);
                }
                else if (propertyName == "Allow")
                {
                    return(Allow);
                }
                else if (propertyName == "Authorization")
                {
                    return(Authorization);
                }
                else if (propertyName == "Cache-Control")
                {
                    return(CacheControl);
                }
                else if (propertyName == "Connection")
                {
                    return(Connection);
                }
                else if (propertyName == "Content")
                {
                    return(Content);
                }
                else if (propertyName == "Content-Disposition")
                {
                    return(ContentDisposition);
                }
                else if (propertyName == "Content-Encoding")
                {
                    return(ContentEncoding);
                }
                else if (propertyName == "Content-Language")
                {
                    return(ContentLanguage);
                }
                else if (propertyName == "Content-Length")
                {
                    return(ContentLength.ToString());
                }
                else if (propertyName == "Content-Location")
                {
                    return(ContentLocation);
                }
                else if (propertyName == "Content-MD5")
                {
                    return(ContentMD5);
                }
                else if (propertyName == "Content-Range")
                {
                    return(ContentRange);
                }
                else if (propertyName == "Content-Type")
                {
                    return(ContentType);
                }
                else if (propertyName == "Date")
                {
                    return(Date);
                }
                else if (propertyName == "Expect")
                {
                    return(Expect);
                }
                else if (propertyName == "Expires")
                {
                    return(Expires);
                }
                else if (propertyName == "From")
                {
                    return(From);
                }
                else if (propertyName == "Host")
                {
                    return(Host);
                }
                else if (propertyName == "If-Match")
                {
                    return(IfMatch);
                }
                else if (propertyName == "If-Modified-Since")
                {
                    return(IfModifiedSince);
                }
                else if (propertyName == "If-None-Match")
                {
                    return(IfNoneMatch);
                }
                else if (propertyName == "If-Range")
                {
                    return(IfRange);
                }
                else if (propertyName == "If-Unmodified-Since")
                {
                    return(IfUnmodifiedSince);
                }
                else if (propertyName == "Last-Modified")
                {
                    return(LastModified);
                }
                else if (propertyName == "Method")
                {
                    return(Method);
                }
                else if (propertyName == "User-Agent")
                {
                    return(UserAgent);
                }
                else if (propertyName == "Version")
                {
                    return(Version);
                }
                else if (propertyName == "Via")
                {
                    return(Via);
                }
                else if (propertyName == "Warning")
                {
                    return(Warning);
                }

                return(null);
            }
            set
            {
                if (propertyName == "Accept")
                {
                    Accept = value;
                }
                else if (propertyName == "Accept-Charset")
                {
                    AcceptCharset = value;
                }
                else if (propertyName == "Accept-Encoding")
                {
                    AcceptEncoding = value;
                }
                else if (propertyName == "Accept-Language")
                {
                    AcceptLanguage = value;
                }
                else if (propertyName == "Allow")
                {
                    Allow = value;
                }
                else if (propertyName == "Authorization")
                {
                    Authorization = value;
                }
                else if (propertyName == "Cache-Control")
                {
                    CacheControl = value;
                }
                else if (propertyName == "Connection")
                {
                    Connection = value;
                }
                else if (propertyName == "Content")
                {
                    Content = value;
                }
                else if (propertyName == "Content-Disposition")
                {
                    ContentDisposition = value;
                }
                else if (propertyName == "Content-Encoding")
                {
                    ContentEncoding = value;
                }
                else if (propertyName == "Content-Language")
                {
                    ContentLanguage = value;
                }
                else if (propertyName == "Content-Length")
                {
                    long contentLength;
                    if (long.TryParse(value, out contentLength))
                    {
                        ContentLength = contentLength;
                    }
                }
                else if (propertyName == "Content-Location")
                {
                    ContentLocation = value;
                }
                else if (propertyName == "Content-MD5")
                {
                    ContentMD5 = value;
                }
                else if (propertyName == "Content-Range")
                {
                    ContentRange = value;
                }
                else if (propertyName == "Content-Type")
                {
                    ContentType = value;
                }
                else if (propertyName == "Date")
                {
                    Date = value;
                }
                else if (propertyName == "Expect")
                {
                    Expect = value;
                }
                else if (propertyName == "Expires")
                {
                    Expires = value;
                }
                else if (propertyName == "From")
                {
                    From = value;
                }
                else if (propertyName == "Host")
                {
                    Host = value;
                }
                else if (propertyName == "If-Match")
                {
                    IfMatch = value;
                }
                else if (propertyName == "If-Modified-Since")
                {
                    IfModifiedSince = value;
                }
                else if (propertyName == "If-None-Match")
                {
                    IfNoneMatch = value;
                }
                else if (propertyName == "If-Range")
                {
                    IfRange = value;
                }
                else if (propertyName == "If-Unmodified-Since")
                {
                    IfUnmodifiedSince = value;
                }
                else if (propertyName == "Last-Modified")
                {
                    LastModified = value;
                }
                else if (propertyName == "Method")
                {
                    Method = value;
                }
                else if (propertyName == "User-Agent")
                {
                    UserAgent = value;
                }
                else if (propertyName == "Version")
                {
                    Version = value;
                }
                else if (propertyName == "Via")
                {
                    Via = value;
                }
                else if (propertyName == "Warning")
                {
                    Warning = value;
                }
            }
        }
        private void SerializeHeaders()
        {
            if (HeadersBuffer == null)
            {
#if DEBUG
                if (HttpTraceHelper.InternalLog.TraceVerbose)
                {
                    HttpTraceHelper.WriteLine("HttpListenerWebResponse#" + HttpTraceHelper.HashString(this) +
                                              "::SerializeHeaders()");
                }
#endif

                //
                // format headers and send them on the wire
                //
                var stringBuilder = new StringBuilder(1024);

                stringBuilder.Append("HTTP/");
                stringBuilder.Append(ProtocolVersion.Major.ToString());
                stringBuilder.Append(".");
                stringBuilder.Append(ProtocolVersion.Minor.ToString());
                stringBuilder.Append(" ");
                stringBuilder.Append(((int)StatusCode).ToString());
                stringBuilder.Append(" ");
                if (StatusDescription == null || StatusDescription.Length == 0)
                {
                    StatusDescription = StatusCode.ToString();
                }
                stringBuilder.Append(StatusDescription);
                stringBuilder.Append("\r\n");

                if (Server != null)
                {
                    Headers["Server"] = Server;
                }
                if (!Date.Equals(DateTime.MinValue))
                {
                    Headers["Date"] = Date.ToString("R");
                }
                if (!KeepAlive)
                {
                    Headers["Connection"] = "Close";
                }
                if (Chunked)
                {
                    Headers.Remove("Content-Length");
                    Headers["Transfer-Encoding"] = "Chunked";
                }
                else
                {
                    Headers["Content-Length"] = ContentLength.ToString("D");
                    Headers.Remove("Transfer-Encoding");
                }

                if (ContentType != null)
                {
                    Headers["Content-Type"] = ContentType;
                }

                if (Headers != null)
                {
                    for (var i = 0; i < Headers.Count; i++)
                    {
                        stringBuilder.Append(Headers.GetKey(i));
                        stringBuilder.Append(": ");
                        stringBuilder.Append(Headers.Get(i));
                        stringBuilder.Append("\r\n");
                    }
                }
                stringBuilder.Append("\r\n");

                if (Request.DelayResponse > 0)
                {
                    //
                    // this feature is useful for testing
                    //
#if DEBUG
                    if (HttpTraceHelper.InternalLog.TraceVerbose)
                    {
                        HttpTraceHelper.WriteLine("HttpListenerWebResponse#" + HttpTraceHelper.HashString(this) +
                                                  "::SerializeHeaders() delaying Response() for:" +
                                                  Request.DelayResponse);
                    }
#endif
                    Thread.Sleep(Request.DelayResponse);
                }

                HeadersBuffer = Encoding.ASCII.GetBytes(stringBuilder.ToString());
            }
        }
Exemplo n.º 14
0
 protected override void SetContentHeaders(StringStringKeyValuePairContainer headers)
 {
     headers.Put(HeaderKeys.ContentType, raw ? EncType.ContentValue : MimeType.GetByFile(fileLink).Notation);
     headers.Put(HeaderKeys.ContentLength, ContentLength.ToString());
 }
Exemplo n.º 15
0
        /// <summary>
        /// Write the request to the stream.
        /// </summary>
        /// <param name="writeEndOfHeaders">Write the end of the header bytes, carrige return line feed.</param>
        public virtual void WriteNetRequestHeaders(bool writeEndOfHeaders = true)
        {
            byte[] buffer = null;
            string data   = "";

            // If content length has been specified.
            if (ContentLength > 0)
            {
                AddHeader("Content-Length", ContentLength.ToString());
            }

            // If the Host been specified.
            if (!String.IsNullOrEmpty(Host))
            {
                AddHeader("Host", Host);
            }

            // If the content type has been specified.
            if (!String.IsNullOrEmpty(ContentType))
            {
                AddHeader("Content-Type", ContentType);
            }

            // If the content encoding has been specified.
            if (AcceptEncoding != null)
            {
                AddHeader("Accept-Encoding", String.Join(",", AcceptEncoding));
            }

            // If the content lanaguage has been specified.
            if (AcceptLanguages != null)
            {
                AddHeader("Accept-Language", String.Join(",", AcceptLanguages));
            }

            // If the content accept types has been specified.
            if (AcceptTypes != null)
            {
                AddHeader("Accept", String.Join(",", AcceptTypes));
            }

            // If the UrlReferrer has been specified.
            if (UrlReferrer != null)
            {
                AddHeader("Referer", UrlReferrer.OriginalString);
            }

            // If the upgrade has been specified.
            if (!String.IsNullOrEmpty(Upgrade))
            {
                // If an upgrade is required
                // then set the connection to upgrade
                // and set the upgrade to the protocol (e.g. WebSocket, HTTP/2.0 .. etc).
                AddHeader("Connection", "Upgrade");
                AddHeader("Upgrade", Upgrade);
            }
            else
            {
                // If the connection is open.
                if (KeepAlive)
                {
                    AddHeader("Connection", "Keep-Alive");
                }
            }

            // If the credentials has been specified.
            if (Credentials != null)
            {
                string userAndPassword  = Credentials.UserName + ":" + Credentials.Password;
                byte[] credentialBytes  = Encoding.Default.GetBytes(userAndPassword);
                string credentialString = Convert.ToBase64String(credentialBytes);
                AddHeader("Authorization", AuthorizationType.ToString() + " " + credentialString);
            }

            // If cookies exist.
            if (Cookies != null)
            {
                string cookieNameValueCol = "";

                // For each cookie found.
                foreach (Cookie cookie in Cookies)
                {
                    // Make shore the cookie has been set.
                    if (!String.IsNullOrEmpty(cookie.Name) && !String.IsNullOrEmpty(cookie.Value))
                    {
                        // Set the name value cookie collection.
                        cookieNameValueCol += cookie.Name + "=" + cookie.Value + ";";
                    }
                }

                // Only set the cookies if a name value exists.
                if (!String.IsNullOrEmpty(cookieNameValueCol))
                {
                    // Add the cookie header.
                    AddHeader("Cookie", cookieNameValueCol.TrimEnd(';'));
                }
            }

            // If protocol version http/2 is used.
            if ((ProtocolVersion.ToLower().Equals("http/2")) || (ProtocolVersion.ToLower().Equals("http/2.0")))
            {
                // Send the http request.
                data   = ":method = " + Method + _deli + ":scheme = " + Scheme + _deli + ":path = " + Path + _deli;
                buffer = Encoding.Default.GetBytes(data);
                Write(buffer, 0, buffer.Length);
            }
            else
            {
                // Send the http request.
                data   = Method + " " + Path + " " + ProtocolVersion + _deli;
                buffer = Encoding.Default.GetBytes(data);
                Write(buffer, 0, buffer.Length);
            }

            // If headers exists.
            if (Headers != null)
            {
                // For each header found.
                foreach (string header in Headers.AllKeys)
                {
                    // If protocol version http/2 is used.
                    if ((ProtocolVersion.ToLower().Equals("http/2")) || (ProtocolVersion.ToLower().Equals("http/2.0")))
                    {
                        // Add each header.
                        data   = header.ToLower() + " = " + Headers[header] + _deli;
                        buffer = Encoding.Default.GetBytes(data);
                        Write(buffer, 0, buffer.Length);
                    }
                    else
                    {
                        // Add each header.
                        data   = header + ": " + Headers[header] + _deli;
                        buffer = Encoding.Default.GetBytes(data);
                        Write(buffer, 0, buffer.Length);
                    }
                }
            }

            // Write the end of the headers.
            if (writeEndOfHeaders)
            {
                // Send the header end space.
                data   = _deli;
                buffer = Encoding.Default.GetBytes(data);
                Write(buffer, 0, buffer.Length);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Write the response status to the stream.
        /// </summary>
        /// <param name="writeEndOfHeaders">Write the end of the header bytes, carrige return line feed.</param>
        /// <param name="writeResponseStatus">Write the response status (HTTP/1.1 200 OK)</param>
        public virtual void WriteWebResponseHeaders(bool writeEndOfHeaders = true, bool writeResponseStatus = true)
        {
            byte[] buffer = null;
            string data   = "";

            // If chunked is used.
            if (SendChunked)
            {
                AddHeader("Transfer-Encoding", "Chunked");
            }

            // If the server has been specified.
            if (!String.IsNullOrEmpty(Server))
            {
                AddHeader("Server", Server);
            }

            // If content length has been specified.
            if (ContentLength > 0)
            {
                AddHeader("Content-Length", ContentLength.ToString());
            }

            // If the allow has been specified.
            if (!String.IsNullOrEmpty(Allow))
            {
                AddHeader("Allow", Allow);
            }

            // If the content type has been specified.
            if (!String.IsNullOrEmpty(ContentType))
            {
                AddHeader("Content-Type", ContentType);
            }

            // If the Upgrade has been specified.
            if (!String.IsNullOrEmpty(Upgrade))
            {
                // If an upgrade is required
                // then set the connection to upgrade
                // and set the upgrade to the protocol (e.g. WebSocket, HTTP/2.0 .. etc).
                AddHeader("Connection", "Upgrade");
                AddHeader("Upgrade", Upgrade);
            }
            else
            {
                // If the connection is open.
                if (KeepAlive)
                {
                    AddHeader("Connection", "Keep-Alive");
                }
            }

            // If the content encoding has been specified.
            if (!String.IsNullOrEmpty(ContentEncoding))
            {
                AddHeader("Content-Encoding", ContentEncoding);
            }

            // If the content lanaguage has been specified.
            if (!String.IsNullOrEmpty(ContentLanguage))
            {
                AddHeader("Content-Language", ContentLanguage);
            }

            // If authenticate type is other than none.
            if (AuthorizationType != Nequeo.Security.AuthenticationType.None)
            {
                AddHeader("WWW-Authenticate", AuthorizationType.ToString());
            }

            // Write response status.
            if (writeResponseStatus)
            {
                // If protocol version http/2 is used.
                if ((ProtocolVersion.ToLower().Equals("http/2")) || (ProtocolVersion.ToLower().Equals("http/2.0")))
                {
                    // Send the http response status.
                    data   = ":status = " + StatusCode.ToString() + (StatusSubcode > 0 ? "." + StatusSubcode.ToString() : "") + _deli;
                    buffer = Encoding.Default.GetBytes(data);
                    Write(buffer, 0, buffer.Length);
                }
                else
                {
                    // Send the http response status.
                    data   = ProtocolVersion + " " + StatusCode.ToString() + (StatusSubcode > 0 ? "." + StatusSubcode.ToString() : "") + " " + StatusDescription + _deli;
                    buffer = Encoding.Default.GetBytes(data);
                    Write(buffer, 0, buffer.Length);
                }
            }

            // If headers exists.
            if (Headers != null)
            {
                // For each header found.
                foreach (string header in Headers.AllKeys)
                {
                    // If protocol version http/2 is used.
                    if ((ProtocolVersion.ToLower().Equals("http/2")) || (ProtocolVersion.ToLower().Equals("http/2.0")))
                    {
                        // Add each header.
                        data   = header.ToLower() + " = " + Headers[header] + _deli;
                        buffer = Encoding.Default.GetBytes(data);
                        Write(buffer, 0, buffer.Length);
                    }
                    else
                    {
                        // Add each header.
                        data   = header + ": " + Headers[header] + _deli;
                        buffer = Encoding.Default.GetBytes(data);
                        Write(buffer, 0, buffer.Length);
                    }
                }
            }

            // If cookies exists.
            if (Cookies != null)
            {
                // For each cookie found.
                foreach (Cookie cookie in Cookies)
                {
                    // Make shore the cookie has been set.
                    if (!String.IsNullOrEmpty(cookie.Name) && !String.IsNullOrEmpty(cookie.Value))
                    {
                        // Get the cookie details.
                        data = "Set-Cookie" + ": " + cookie.Name + "=" + cookie.Value +
                               (cookie.Expires != null ? "; Expires=" + cookie.Expires.ToUniversalTime().ToLongDateString() + " " + cookie.Expires.ToUniversalTime().ToLongTimeString() + " GMT" : "") +
                               (!String.IsNullOrEmpty(cookie.Path) ? "; Path=" + cookie.Path : "") +
                               (!String.IsNullOrEmpty(cookie.Domain) ? "; Domain=" + cookie.Domain : "") +
                               (cookie.Version > 0 ? "; Version=" + cookie.Version : "") +
                               (cookie.Secure ? "; Secure" : "") +
                               (cookie.HttpOnly ? "; HttpOnly" : "") +
                               _deli;

                        // Write to the stream.
                        buffer = Encoding.Default.GetBytes(data);
                        Write(buffer, 0, buffer.Length);
                    }
                }
            }

            // Write the end of the headers.
            if (writeEndOfHeaders)
            {
                // Send the header end space.
                data   = _deli;
                buffer = Encoding.Default.GetBytes(data);
                Write(buffer, 0, buffer.Length);
            }
        }
Exemplo n.º 17
0
 protected virtual void SetContentHeaders(StringStringKeyValuePairContainer headers)
 {
     headers.Put(HeaderKeys.ContentType, EncType.ContentValue);
     headers.Put(HeaderKeys.ContentLength, ContentLength.ToString());
 }