public string FormatError(HttpStatusCode code, string description)
 {
     var template = AppDomain.CurrentDomain.BaseDirectory + "\\content\\error_template.tpl";
     if (File.Exists(template))
     {
         var templateContent = File.ReadAllText(template);
         templateContent = templateContent.Replace("{data:code}", ((int) code).ToString()).Replace(
             "{data:description}", description);
         return templateContent;
     }
     return "";
 }
Beispiel #2
0
 public static string Stringify(HttpStatusCode code)
 {
     switch (code)
     {
         case HttpStatusCode.Accepted: return "Accepted";
         case HttpStatusCode.Ambiguous: return "Multiple Choices";
         case HttpStatusCode.BadGateway: return "Bad Gateway";
         case HttpStatusCode.BadRequest: return "Bad Request";
         case HttpStatusCode.Conflict: return "Conflict";
         case HttpStatusCode.Continue: return "Continue";
         case HttpStatusCode.Created: return "Created";
         case HttpStatusCode.ExpectationFailed: return "Expectation Failed";
         case HttpStatusCode.Forbidden: return "Forbidden";
         case HttpStatusCode.Found: return "Found";
         case HttpStatusCode.GatewayTimeout: return "Gateway Timeout";
         case HttpStatusCode.Gone: return "Gone";
         case HttpStatusCode.HttpVersionNotSupported: return "HTTP Version Not Supported";
         case HttpStatusCode.InternalServerError: return "Internal Server Error";
         case HttpStatusCode.LengthRequired: return "Length Required";
         case HttpStatusCode.MethodNotAllowed: return "Method Not Allowed";
         case HttpStatusCode.Moved: return "Moved";
         case HttpStatusCode.NoContent: return "No Content";
         case HttpStatusCode.NonAuthoritativeInformation: return "Non Authoritative Information";
         case HttpStatusCode.NotAcceptable: return "Not Acceptable";
         case HttpStatusCode.NotFound: return "Not Found";
         case HttpStatusCode.NotImplemented: return "Not Implemented";
         case HttpStatusCode.NotModified: return "Not Modified";
         case HttpStatusCode.OK: return "OK";
         case HttpStatusCode.PartialContent: return "Partial Content";
         case HttpStatusCode.PaymentRequired: return "Payment Required";
         case HttpStatusCode.PreconditionFailed: return "Precondition Failed";
         case HttpStatusCode.ProxyAuthenticationRequired: return "Proxy Authentication Required";
         case HttpStatusCode.RedirectKeepVerb: return "Redirect Keep Verb";
         case HttpStatusCode.RedirectMethod: return "Redirect Method";
         case HttpStatusCode.RequestedRangeNotSatisfiable: return "Requested Range Not Satisfiable";
         case HttpStatusCode.RequestEntityTooLarge: return "Request Entity Too Large";
         case HttpStatusCode.RequestTimeout: return "Request Timeout";
         case HttpStatusCode.RequestUriTooLong: return "Request URI Too Long";
         case HttpStatusCode.ResetContent: return "Reset Content";
         case HttpStatusCode.ServiceUnavailable: return "Service Unavailable";
         case HttpStatusCode.SwitchingProtocols: return "Switching Protocols";
         case HttpStatusCode.Unauthorized: return "Unauthorized";
         case HttpStatusCode.UnsupportedMediaType: return "Unsupported Media Type";
         case HttpStatusCode.Unused: return "Unused";
         case HttpStatusCode.UseProxy: return "Use Proxy";
         default: return code.ToString();
     }
 }
Beispiel #3
0
            internal void _BeginResponse(HttpResponse response, HttpStatusCode status, Action<HttpBuffer> ev_buffer, Action/*?*/ ev_done = null)
            {
                lock (_server._lock) {
                    if (_isdisposed) return;    // this is not the right place to throw
                    if (_state != _State.ResponseHeadersUserWait && _state != _State.RequestBodyUserWait)
                        throw new InvalidOperationException("invalid state for response body streaming (" + _state + ")");
                    if (_responsebody_streaming_started)
                        throw new InvalidOperationException("request body can only be streamed once");
                    if (_tx == null || _tx.Response != response)
                        throw new InvalidOperationException("this request object is not active");

                    _server.ev_debug("begin response");
                    _responsebody_buffer            = new ResponseBodyBuffer(this);
                    _responsebody_user_cb           = ev_buffer;
                    if (_responsebody_done_cb != null) throw new InvalidOperationException("resources may have leaked");
                    _responsebody_done_cb           = ev_done;

                    if (!response.Headers.ContentLength.HasValue && !_ishttp10) {
                        response.Headers.SetChunkedEncoding();
                    }

                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("HTTP/{0} {1} {2}\r\n", (_ishttp10?"1.0":"1.1"), (int)status, _Utils.Stringify(status));
                    response.Headers.Write(sb, response.Cookies.Values);

                    _server.ev_debug("{0}", sb.ToString());
                    _server.ev_debug("--------------------------------------");

                    _responsebody_left = response.Headers.ContentLength ?? -1;
                    _writebytes        = Encoding.UTF8.GetBytes(sb.ToString());
                    _writecount        = _writebytes.Length;
                    _writeoff          = 0;
                    if (_state == _State.RequestBodyUserWait) {         // if we are still waiting for the user to read the request body, dump it
                        _state = _State.RequestBodyDump;
                    } else {
                        _state = _State.SendResponseHeaders;
                    }
                    _HandleCurrentState();
                }
            }
Beispiel #4
0
 void _Respond(HttpStatusCode status, byte[] body)
 {
     Headers.ContentLength = body.Length;
     _connection._BeginResponse(this, status, buf => {
         buf.Buffer       = body;
         buf.Offset       = 0;
         buf.Count        = body.Length;
         buf.IsLastBuffer = true;
         buf.Complete();
     });
 }
Beispiel #5
0
 void _Respond(HttpStatusCode status, Stream body)
 {
     Headers.ContentLength = body.Length;
     byte[] buf = new byte[32768];
     BeginResponse(HttpStatusCode.OK,
                   ev_buffer: responsebuf => {
                       responsebuf.Buffer = buf;
                       responsebuf.Offset = 0;
                       responsebuf.Count  = body.Read(buf, 0, buf.Length);
                       if (body.Position == body.Length)
                           responsebuf.IsLastBuffer = true;
                       responsebuf.Complete();
                   },
                   ev_done: () => {
                       try { body.Close(); } catch { }
                   });
 }
 /// <summary>
 /// Send a response.
 /// </summary>
 /// <param name="httpVersion">Either <see cref="HttpHelper.HTTP10"/> or <see cref="HttpHelper.HTTP11"/></param>
 /// <param name="statusCode">HTTP status code</param>
 /// <param name="reason">reason for the status code.</param>
 public void Respond(string httpVersion, HttpStatusCode statusCode, string reason)
 {
     Respond(httpVersion, statusCode, reason, null, null);
 }
 public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType) {Console.WriteLine("xxxxxx");}
Beispiel #8
0
 public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType) {}
Beispiel #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpException"/> class.
 /// </summary>
 /// <param name="code">HTTP status code.</param>
 /// <param name="errMsg">Exception description.</param>
 public HttpException(HttpStatusCode code, string errMsg)
     : base(errMsg)
 {
     Code = code;
 }
Beispiel #10
0
 public void Respond(HttpStatusCode status)
 {
     _Respond(status);
 }
Beispiel #11
0
 public void Respond(HttpStatusCode status, Stream body)
 {
     _Respond(status, body);
 }
Beispiel #12
0
 public void Respond(HttpStatusCode status, byte[] body)
 {
     _Respond(status, body);
 }
Beispiel #13
0
 public void Respond(HttpStatusCode status, string body)
 {
     _Respond(status, body);
 }
Beispiel #14
0
 //
 // To send a response all at once, use one of these Respond overloads
 //
 public void Respond(HttpStatusCode status, string body, params object[] ps)
 {
     _Respond(status, string.Format(body,ps));
 }
Beispiel #15
0
 //
 // To send a streaming respond, call BeginResponse.
 //
 // Once the client is ready to consume buffers, cb_buffer will be invoked with an HttpBuffer object.
 //
 // Fill in the Buffer, Offset, and Count fields on this object, then call HttpBuffer.Complete() to pass
 // the buffer to the client.
 //
 // When you have filled the last buffer, set the IsLastBuffer property to true. This will complete the
 // HTTP response.
 //
 // Streaming responses are always sent using chunked transfer encoding.
 //
 public void BeginResponse(HttpStatusCode status, 
                           Action<HttpBuffer> ev_buffer,
                           Action             ev_done = null)
 {
     _connection._BeginResponse(this, status, ev_buffer, ev_done);
 }
        /// <summary>
        /// Send a response.
        /// </summary>
        /// <param name="httpVersion">Either HttpHelper.HTTP10 or HttpHelper.HTTP11</param>
        /// <param name="statusCode">http status code</param>
        /// <param name="reason">reason for the status code.</param>
        /// <param name="body">html body contents, can be null or empty.</param>
        /// <param name="contentType">A content type to return the body as, ie 'text/html' or 'text/plain', defaults to 'text/html' if null or empty</param>
        /// <exception cref="ArgumentException">If httpVersion is invalid.</exception>
        public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType)
        {
            if (string.IsNullOrEmpty(contentType))
                contentType = "text/html";

            if (string.IsNullOrEmpty(httpVersion))
                throw new ArgumentException("Invalid HTTP version");

            if (string.IsNullOrEmpty(reason))
                reason = statusCode.ToString();

            byte[] buffer;
            if (string.IsNullOrEmpty(body))
            {
                buffer = Encoding.ASCII.GetBytes(String.Format("{0} {1} {2}\r\n\r\n",
                    httpVersion, (int)statusCode, reason));
            }
            else
            {
                buffer = Encoding.ASCII.GetBytes(String.Format("{0} {1} {2}\r\nContent-Type: {3}\r\nContent-Length: {4}\r\n\r\n{5}",
                    httpVersion, (int)statusCode, reason, contentType, body.Length, body));
            }

            Send(buffer);
        }
Beispiel #17
0
 public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) {}
Beispiel #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpException"/> class.
 /// </summary>
 /// <param name="code">HTTP status code.</param>
 /// <param name="errMsg">Exception description.</param>
 /// <param name="inner">Inner exception.</param>
 protected HttpException(HttpStatusCode code, string errMsg, Exception inner)
     : base(errMsg, inner)
 {
     Code = code;
 }
 public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) {Console.WriteLine("xx");}
Beispiel #20
0
            void _Fail(HttpStatusCode code)
            {
                var response      = string.Format("HTTP/1.1 {0} {1}\r\nContent-Length: 0\r\n\r\n", (int)code, _Utils.Stringify(code));
                var responsebytes = Encoding.UTF8.GetBytes(response);

                _state      = _State.Failure;
                _writeoff   = 0;
                _writecount = responsebytes.Length;
                _writebytes = responsebytes;
            }
        /// <summary>
        /// Send a response.
        /// </summary>
        /// <param name="httpVersion">Either <see cref="HttpHelper.HTTP10"/> or <see cref="HttpHelper.HTTP11"/></param>
        /// <param name="statusCode">HTTP status code</param>
        /// <param name="reason">reason for the status code.</param>
        /// <param name="body">HTML body contents, can be null or empty.</param>
        /// <param name="contentType">A content type to return the body as, i.e. 'text/html' or 'text/plain', defaults to 'text/html' if null or empty</param>
        /// <exception cref="ArgumentException">If <paramref name="httpVersion"/> is invalid.</exception>
        public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType)
        {
            if (string.IsNullOrEmpty(contentType))
                contentType = "text/html";

            if (string.IsNullOrEmpty(httpVersion) || !httpVersion.StartsWith("HTTP/1"))
                throw new ArgumentException("Invalid HTTP version");

            if (string.IsNullOrEmpty(reason))
                reason = statusCode.ToString();

            string response = string.IsNullOrEmpty(body)
                                  ? httpVersion + " " + (int) statusCode + " " + reason + "\r\n\r\n"
                                  : string.Format("{0} {1} {2}\r\nContent-Type: {5}\r\nContent-Length: {3}\r\n\r\n{4}",
                                                  httpVersion, (int) statusCode, reason ?? statusCode.ToString(),
                                                  body.Length, body, contentType);
            byte[] buffer = Encoding.ASCII.GetBytes(response);

            Send(buffer);
        }
Beispiel #22
0
 void _Respond(HttpStatusCode status, string body)
 {
     _Respond(status, Encoding.UTF8.GetBytes(body));
 }
Beispiel #23
0
		/// <summary>
		/// Generate a HTTP error page (that will be added to the response body).
		/// response status code is also set.
		/// </summary>
		/// <param name="response">Response that the page will be generated in.</param>
		/// <param name="error"><see cref="HttpStatusCode"/>.</param>
		/// <param name="body">response body contents.</param>
		protected virtual void ErrorPage(IHttpResponse response, HttpStatusCode error, string body)
		{
			response.Reason = "Internal server error";
			response.Status = error;
			response.ContentType = "text/plain";

			StreamWriter writer = new StreamWriter(response.Body);
			writer.WriteLine(body);
			writer.Flush();
		}
Beispiel #24
0
 void _Respond(HttpStatusCode status)
 {
     _Respond(status, new byte[0]);
 }