Ejemplo n.º 1
0
 internal static void WriteResponse(this HttpListenerResponse response, HandlerProcessResult result)
 {
     response.StatusCode = (int)result.StatusCode;
     if (!string.IsNullOrEmpty(result.ContentType) &&
         result.Content != null)
     {
         response.ContentEncoding = HandlerProcessResult.ContentEncoding;
         response.ContentLength64 = result.Content.LongLength;
         response.ContentType     = result.ContentType;
         response.OutputStream.Write(result.Content, 0, result.Content.Length);
     }
 }
Ejemplo n.º 2
0
        private void ProcessRequest(HttpListenerContext context)
        {
            var incorrectResults = new List <Tuple <IRaspkateHandler, HandlerProcessResult> >();

            foreach (var handler in this.handlers)
            {
                try
                {
                    if (handler.ShouldHandle(context.Request))
                    {
                        var result = handler.Process(context.Request);
                        if (result.StatusCode == HttpStatusCode.OK)
                        {
                            context.Response.WriteResponse(result);
                            return;
                        }
                        else
                        {
                            incorrectResults.Add(new Tuple <IRaspkateHandler, HandlerProcessResult>(handler, result));
                        }
                    }
                    else
                    {
                        log.DebugFormat("Handler \"{0}\" cannot handle the request with URL \"{1}\", skipped.", handler, context.Request.Url);
                    }
                }
                catch (Exception ex)
                {
                    log.Warn(string.Format("Failed to check whether the current handler (Handler: \"{0}\") can handle the given request, skipping...", handler), ex);
                }
            }

            if (incorrectResults.Count == 0)
            {
                context.Response.WriteResponse(HandlerProcessResult.Text(HttpStatusCode.BadRequest, "Invalid request."));
            }
            else if (incorrectResults.Count == 1)
            {
                context.Response.WriteResponse(incorrectResults[0].Item2);
            }
            else
            {
                var groupings = incorrectResults.GroupBy(x => x.Item2.StatusCode);
                if (groupings.Count() == 1)
                {
                    context.Response.WriteResponse(groupings.First().Key, incorrectResults);
                }
                else
                {
                    context.Response.WriteResponse(HttpStatusCode.InternalServerError, incorrectResults);
                }
            }
        }