コード例 #1
0
        protected override void ProcessRequest(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl))
            {
                return;
            }

            var operationName = context.Request.GetOperationName();

            var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
            var httpRes = new HttpListenerResponseWrapper(context.Response);
            var handler = ServiceStackHttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHttpHandler;

            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.Name;
                }
                serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
                httpRes.Close();
                return;
            }

            throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
        }
コード例 #2
0
        protected override void ProcessRequest(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl))
            {
                return;
            }

            var operationName = context.Request.GetOperationName();
            var httpMethod    = context.Request.HttpMethod;
            var queryString   = context.Request.QueryString;
            var inputStream   = context.Request.InputStream;
            var response      = new HttpListenerResponseWrapper(context.Response);

            var url = context.Request.Url.PathAndQuery.ToLower();

            if (url.Contains("/xml/"))
            {
                ProcessXmlRequest(url, operationName, httpMethod, queryString, inputStream, response);
            }
            else if (url.Contains("/json/"))
            {
                ProcessJsonRequest(url, operationName, httpMethod, queryString, inputStream, response);
            }
            else if (url.Contains("/jsv/"))
            {
                ProcessJsvRequest(url, operationName, httpMethod, queryString, inputStream, response);
            }
        }
コード例 #3
0
        protected override void ProcessRequest(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl))
            {
                return;
            }

            var operationName = context.Request.GetOperationName();
            var request       = CreateRequest(context.Request, operationName);

            const EndpointAttributes endpointAttributes = EndpointAttributes.SyncReply | EndpointAttributes.Xml;

            var result = ExecuteService(request, endpointAttributes);

            var response = new HttpListenerResponseWrapper(context.Response);

            response.WriteToResponse(result, x => DataContractSerializer.Instance.Parse(result), ContentType.Xml);
        }
コード例 #4
0
 public HttpListenerContextWrapper(HttpListenerContext context)
 {
     this.context = context;
     request      = new HttpListenerRequestWrapper(context.Request);
     response     = new HttpListenerResponseWrapper(context.Response);
 }
コード例 #5
0
        // Handle the processing of a request in here.
        private void ListenerCallback(IAsyncResult asyncResult)
        {
            var listener = asyncResult.AsyncState as HttpListener;
            HttpListenerContext context = null;

            if (listener == null)
            {
                return;
            }

            try
            {
                if (!IsListening)
                {
                    Log.DebugFormat("Ignoring ListenerCallback() as HttpListener is no longer listening");
                    return;
                }
                // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework,
                // blocks until there is a request to be processed or some type of data is available.
                context = listener.EndGetContext(asyncResult);
            }
            catch (Exception ex)
            {
                // You will get an exception when httpListener.Stop() is called
                // because there will be a thread stopped waiting on the .EndGetContext()
                // method, and again, that is just the way most Begin/End asynchronous
                // methods of the .NET Framework work.
                var errMsg = ex + ": " + IsListening;
                Log.Warn(errMsg);
                return;
            }
            finally
            {
                // Once we know we have a request (or exception), we signal the other thread
                // so that it calls the BeginGetContext() (or possibly exits if we're not
                // listening any more) method to start handling the next incoming request
                // while we continue to process this request on a different thread.
                ListenForNextRequest.Set();
            }

            if (context == null)
            {
                return;
            }

            Log.InfoFormat("{0} Request : {1}", context.Request.UserHostAddress, context.Request.RawUrl);

            //System.Diagnostics.Debug.WriteLine("Start: " + requestNumber + " at " + DateTime.UtcNow);
            //var request = context.Request;

            //if (request.HasEntityBody)

            RaiseReceiveWebRequest(context);

            try
            {
                this.ProcessRequest(context);
            }
            catch (Exception ex)
            {
                var error = string.Format("Error this.ProcessRequest(context): [{0}]: {1}", ex.GetType().Name, ex.Message);
                Log.ErrorFormat(error);

                try
                {
                    var errorResponse = new ErrorResponse
                    {
                        ResponseStatus = new ResponseStatus
                        {
                            ErrorCode  = ex.GetType().Name,
                            Message    = ex.Message,
                            StackTrace = ex.StackTrace,
                        }
                    };

                    var operationName = context.Request.GetOperationName();
                    var httpReq       = new HttpListenerRequestWrapper(operationName, context.Request);
                    var httpRes       = new HttpListenerResponseWrapper(context.Response);
                    var requestCtx    = new HttpRequestContext(httpReq, httpRes, errorResponse);
                    var contentType   = requestCtx.ResponseContentType;

                    var serializer = EndpointHost.ContentTypeFilter.GetResponseSerializer(contentType);
                    if (serializer == null)
                    {
                        contentType = EndpointHost.Config.DefaultContentType;
                        serializer  = EndpointHost.ContentTypeFilter.GetResponseSerializer(contentType);
                    }

                    httpRes.StatusCode  = 500;
                    httpRes.ContentType = contentType;

                    serializer(requestCtx, errorResponse, httpRes);

                    httpRes.Close();
                }
                catch (Exception errorEx)
                {
                    error = string.Format("Error this.ProcessRequest(context)(Exception while writing error to the response): [{0}]: {1}", errorEx.GetType().Name, errorEx.Message);
                    Log.ErrorFormat(error);
                }
            }

            //System.Diagnostics.Debug.WriteLine("End: " + requestNumber + " at " + DateTime.UtcNow);
        }
コード例 #6
0
        protected override void ProcessRequest(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl))
            {
                return;
            }

            var operationName = context.Request.GetOperationName();

            var    httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
            string pathInfo;
            string servicePath;

            AntServiceStackHttpHandlerFactory.GetServicePathInfo(httpReq.PathInfo, out servicePath, out pathInfo);
            httpReq.SetServicePath(servicePath);
            var httpRes = new HttpListenerResponseWrapper(context.Response);

            HostContext.InitRequest(httpReq, httpRes);

            var handler             = AntServiceStackHttpHandlerFactory.GetHandler(httpReq);
            var serviceStackHandler = handler as IServiceStackHttpHandler;

            if (serviceStackHandler != null)
            {
                var endpointHandler = serviceStackHandler as EndpointHandlerBase;
                if (endpointHandler != null)
                {
                    httpReq.OperationName = operationName = endpointHandler.RequestName;
                    if (!string.IsNullOrWhiteSpace(operationName))
                    {
                        bool isAsync = EndpointHost.MetadataMap[endpointHandler.ServicePath.ToLower()].OperationNameMap[operationName.ToLower()].IsAsync;
                        if (isAsync)
                        {
                            var task = endpointHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                            task.ContinueWith(t =>
                            {
                                try
                                {
                                    if (t.Exception != null)
                                    {
                                        log.Error("Error happened in async service execution!", t.Exception.InnerException ?? t.Exception,
                                                  new Dictionary <string, string>()
                                        {
                                            { "ErrorCode", "FXD300079" }, { "HostMode", "Self-Host" }
                                        });
                                    }
                                    httpRes.Close();
                                }
                                catch {  }
                            });
                            return;
                        }
                    }
                }

                serviceStackHandler.ProcessRequest(httpReq, httpRes, operationName);
                httpRes.Close();
                return;
            }

            throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo);
        }
コード例 #7
0
ファイル: WebAppServer.cs プロジェクト: jbdk/WebAppHost
        private Task ProcessRequestAsync(HttpListenerContext context)
        {
            try
            {
                Debug.WriteLine("Server: Incoming request to {0}.", context.Request.Url);

                PersistentConnection connection;

                string path = ResolvePath(context.Request.Url);

                foreach (var embeddedFileHandler in _embeddedFileHandlers)
                {
                    var result = embeddedFileHandler.Handle(path, context);
                    if (result != null)
                    {
                        return(result);
                    }
                }

                if (_routingHost.TryGetConnection(path, out connection))
                {
                    // https://developer.mozilla.org/En/HTTP_Access_Control
                    string origin = context.Request.Headers["Origin"];
                    if (!String.IsNullOrEmpty(origin))
                    {
                        context.Response.AddHeader("Access-Control-Allow-Origin", origin);
                        context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                    }

                    var request     = new HttpListenerRequestWrapper(context);
                    var response    = new HttpListenerResponseWrapper(context.Response, _disconnectHandler.GetDisconnectToken(context));
                    var hostContext = new HostContext(request, response);

#if NET45
                    hostContext.Items[HostConstants.SupportsWebSockets] = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 2;
#endif

                    if (OnProcessRequest != null)
                    {
                        OnProcessRequest(hostContext);
                    }

#if DEBUG
                    hostContext.Items[HostConstants.DebugMode] = true;
#endif
                    hostContext.Items["System.Net.HttpListenerContext"] = context;

                    // Initialize the connection
                    connection.Initialize(_routingHost.DependencyResolver);

                    return(connection.ProcessRequestAsync(hostContext));
                }

                if (path.Equals("/clientaccesspolicy.xml", StringComparison.InvariantCultureIgnoreCase))
                {
                    using (var stream = typeof(WebAppServer).Assembly.GetManifestResourceStream(typeof(WebAppServer), "clientaccesspolicy.xml"))
                    {
                        if (stream == null)
                        {
                            var response = new HttpResponseMessage(HttpStatusCode.NotFound);
                            return(context.SendResponseAsync(response));
                        }
                        var bytes     = new byte[1024];
                        int byteCount = stream.Read(bytes, 0, bytes.Length);
                        return(context.Response.WriteAsync(new ArraySegment <byte>(bytes, 0, byteCount)));
                    }
                }

                HttpRequestMessage requestMessage = context.GetHttpRequestMessage();

                return(_webApiServer.PublicSendAsync(requestMessage, _disconnectHandler.GetDisconnectToken(context))
                       .Then(response =>
                {
                    var responseMessage = response ?? new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        RequestMessage = requestMessage
                    };
                    return context.SendResponseAsync(responseMessage);
                }));
            }
            catch (Exception ex)
            {
                return(TaskAsyncHelper.FromError(ex));
            }
        }
コード例 #8
0
        private void ProcessJsonRequest(string url, string operationName, string httpMethod, NameValueCollection queryString, Stream inputStream, HttpListenerResponseWrapper response)
        {
            try
            {
                var request = JsonHandlerBase.CreateRequest(operationName,
                                                            httpMethod, queryString, null, inputStream);

                if (url.Contains("/json/syncreply/"))
                {
                    var result = ExecuteService(request, EndpointAttributes.SyncReply | EndpointAttributes.Json | HttpMethods.GetEndpointAttribute(httpMethod));
                    response.WriteToResponse(result, x => JsonDataContractSerializer.Instance.Parse(result), ContentType.Json);
                }
                else if (url.Contains("/json/asynconeway/"))
                {
                    var result = ExecuteService(request, EndpointAttributes.AsyncOneWay | EndpointAttributes.Json | HttpMethods.GetEndpointAttribute(httpMethod));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                response.WriteJsonErrorToResponse(operationName, ex.Message, ex);
            }
        }
コード例 #9
0
        private void ProcessJsvRequest(string url, string operationName, string httpMethod, NameValueCollection queryString, Stream inputStream, HttpListenerResponseWrapper response)
        {
            try
            {
                var request = JsvHandlerBase.CreateRequest(operationName, httpMethod, queryString, null, inputStream);

                var isDebugRequest = queryString["debug"] != null;

                var writeFn = isDebugRequest
                                        ? (Func <object, string>)JsvFormatter.SerializeAndFormat
                                        : TypeSerializer.SerializeToString;

                var contentType = isDebugRequest ? ContentType.PlainText : ContentType.JsvText;

                if (url.Contains("/jsv/syncreply/"))
                {
                    var result = ExecuteService(request, EndpointAttributes.SyncReply | EndpointAttributes.Jsv | HttpMethods.GetEndpointAttribute(httpMethod));
                    response.WriteToResponse(result, writeFn, contentType);
                }
                else if (url.Contains("/jsv/asynconeway/"))
                {
                    ExecuteService(request, EndpointAttributes.AsyncOneWay | EndpointAttributes.Jsv | HttpMethods.GetEndpointAttribute(httpMethod));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                response.WriteJsvErrorToResponse(operationName, ex.Message, ex);
            }
        }