Example #1
0
        /// <summary>
        /// Initializes an instance of MockServer.
        /// </summary>
        /// <param name="endPoint">The endpoint of the server.</param>
        public MockServer(string endPoint)
        {
            _endPoint = endPoint;
            _listener = new HttpListener();
            _listener.Prefixes.Add(endPoint);

            _get = new RouteTable();
            _put = new RouteTable();
            _delete = new RouteTable();
        }
Example #2
0
        void GenerateResponse(HttpListenerContext context)
        {
            var request = context.Request;
            HttpListenerResponse response = context.Response;

            try
            {
                RouteTable m = null;
                if (request.HttpMethod == "GET")
                {
                    m = _get;
                }
                else if (request.HttpMethod == "PUT")
                {
                    m = _put;
                }
                else if (request.HttpMethod == "DELETE")
                {
                    m = _delete;
                }

                if (m == null)
                {
                    SetResponseNotFound(response);
                }
                else
                {
                    var f = m.Match(request);
                    if (f != null)
                    {
                        var r = f(request);
                        if (r is string)
                        {
                            SetResponseContent(response, (string)r);
                        }
                        else if (r is Action <HttpListenerResponse> )
                        {
                            var action = (Action <HttpListenerResponse>)r;
                            action(response);
                        }
                        else if (r is Action <HttpListenerResponse, IPrincipal> )
                        {
                            var action = (Action <HttpListenerResponse, IPrincipal>)r;
                            action(response, context.User);
                        }
                        else if (r is int || r is HttpStatusCode)
                        {
                            response.StatusCode = (int)r;
                        }
                    }
                    else
                    {
                        SetResponseNotFound(response);
                    }
                }
            }
            finally
            {
                response.OutputStream.Close();
            }
        }