WriteError() public method

Sends a nicely-formatted error with specified HTTP Error Code and Error Message to the client. This response is not buffered and thus calling this method will immediately send the response to the client.
public WriteError ( HTTPStatusCode errorCode, string errorMessage ) : void
errorCode HTTPStatusCode The HTTP Status Code to send
errorMessage string The Error Message to send. For example "Not Found" or "Not Supported"
return void
Esempio n. 1
0
        internal void HandleRequest(HTTPRequest request, HTTPResponse response, Stream stream)
        {
            try
            {
                bool        matchFound = false;
                RouteMapper mapper     = null;
                int         i          = 0;

                for (;;)
                {
                    lock (_routes)
                    {
                        if (i < _routes.Count)
                        {
                            mapper = _routes[i++];
                        }
                        else
                        {
                            break;
                        }
                    }
                    string regex = "^" + mapper.Route;
                    if (!mapper.AcceptSubroutes)
                    {
                        regex += "$";
                    }
                    if (Regex.IsMatch(request.BaseURL, regex))
                    {
                        if ((mapper.Methods & request.Method) != 0)
                        {
                            if (mapper.AcceptSubroutes)
                            {
                                int pos = request.BaseURL.IndexOf(mapper.Route);
                                request.Subroute = request.BaseURL.Substring(0, pos) + request.BaseURL.Substring(pos + mapper.Route.Length);
                            }
                            matchFound = true;
                            break;
                        }
                    }
                }

                if (!matchFound)
                {
                    response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                    response.Respond(stream);
                    OnError(RoutingErrorType.NO_MATCHES, "No route found for request", request);
                }
                else
                {
                    mapper.HandleRequest(request, response);
                    response.Respond(stream);
                }
            }
            catch (Exception e)
            {
                response.WriteError(HTTPStatusCode.InternalServerError, String.Format("Internal Server Error {0}", e.Message));
                response.Respond(stream);
                OnError(RoutingErrorType.INTERNAL, "A RouteHandler threw an exception.", request);
            }
        }
 private void RespondResource(HTTPResponse response, Assembly assembly, string subRoute)
 {
     if (subRoute != "")
     {
         string requestedFile = ResourcePath(subRoute);
         if (_baseDirectory != "")
         {
             if (requestedFile != "")
             {
                 requestedFile = _baseDirectory + ResourcePathSeparator + requestedFile;
             }
             else
             {
                 requestedFile = _baseDirectory;
             }
         }
         // Does this resource exist?
         if (!ServeEmbeddedResource(response, assembly, requestedFile))
         {
             string indexHtmlFileResource = requestedFile + ResourcePathSeparator + "index.html";
             //Try to get 'index.html', maybe?
             if (!ServeEmbeddedResource(response, assembly, indexHtmlFileResource))
             {
                 response.WriteError(HTTPStatusCode.NotFound,
                                     string.Format("Resource not Found at '{0}'", subRoute));
             }
         }
     }
     else
     {
         //If there really is no file requested, then we send a 404!
         response.WriteError(HTTPStatusCode.NotFound,
                             string.Format("Resource not Found at '{0}'", subRoute));
     }
 }
Esempio n. 3
0
        private void HandleRequest(WoopsaVerb verb, HTTPRequest request, HTTPResponse response)
        {
            try
            {
                // This is the first thing we do, that way even 404 errors have the right headers
                if (AllowCrossOrigin)
                {
                    // TODO: constantes symboliques
                    response.SetHeader("Access-Control-Allow-Origin", "*");
                }
                string result = null;
                ExecuteBeforeWoopsaModelAccess();
                try
                {
                    switch (verb)
                    {
                    case WoopsaVerb.Meta:
                        result = GetMetadata(request.Subroute);
                        break;

                    case WoopsaVerb.Read:
                        result = ReadValue(request.Subroute);
                        break;

                    case WoopsaVerb.Write:
                        result = WriteValue(request.Subroute, request.Body["value"]);
                        break;

                    case WoopsaVerb.Invoke:
                        result = InvokeMethod(request.Subroute, request.Body);
                        break;
                    }
                }
                finally
                {
                    ExecuteAfterWoopsaModelAccess();
                }
                response.SetHeader(HTTPHeader.ContentType, MIMETypes.Application.JSON);
                if (result != null)
                {
                    response.WriteString(result);
                }
            }
            catch (WoopsaNotFoundException e)
            {
                response.WriteError(HTTPStatusCode.NotFound, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
            }
            catch (WoopsaInvalidOperationException e)
            {
                response.WriteError(HTTPStatusCode.BadRequest, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
            }
            catch (WoopsaException e)
            {
                response.WriteError(HTTPStatusCode.InternalServerError, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
            }
            catch (Exception e)
            {
                response.WriteError(HTTPStatusCode.InternalServerError, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
            }
        }
        public void HandleRequest(HTTPRequest request, HTTPResponse response)
        {
            if (request.Subroute == "")
            {
                //If there really is no file requested, then we send a 404!
                response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                return;
            }

            lock (_dictionary)
            {
                if (_dictionary.TryGetValue(request.Subroute, out MemoryStream resource))
                {
                    resource.Position = 0;
                    response.WriteStream(resource);
                    response.SetHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                    response.SetHeader("Pragma", "no-cache");
                    response.SetHeader("Expires", "0");
                }
                else
                {
                    response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                }
            }
        }
        public virtual bool Process(HTTPRequest request, HTTPResponse response)
        {
            string username;
            string password;
            bool   authenticated;

            _currentUserName = null;
            if (request.Headers.ContainsKey(HTTPHeader.Authorization))
            {
                string authString = request.Headers[HTTPHeader.Authorization].Split(' ')[1];
                authString = Encoding.GetEncoding("ISO-8859-1").GetString(Convert.FromBase64String(authString));
                string[] parts = authString.Split(':');
                username = parts[0];
                password = parts[1];
            }
            else
            {
                username = null;
                password = null;
            }
            authenticated = Authenticate(request, username, password);
            if (authenticated)
            {
                _currentUserName = username;
            }
            else
            {
                response.SetHeader(HTTPHeader.WWWAuthenticate, "Basic Realm=\"" + Realm + "\"");
                response.WriteError(HTTPStatusCode.Unauthorized, "Unauthorized");
            }
            return(authenticated);
        }
        public void HandleRequest(HTTPRequest request, HTTPResponse response)
        {
            string subRoute = request.Subroute;

            if (_assembly != null)
            {
                RespondResource(response, _assembly, subRoute);
            }
            else
            {
                Assembly assembly;
                // First element = initial /
                string[] pathParts = subRoute.Split(new char[] { WoopsaConst.UrlSeparator }, 3);
                if (pathParts.Length == 3 && pathParts[1] != "")
                {
                    assembly = AssemblyByName(pathParts[1]);
                }
                else
                {
                    assembly = null;
                }
                if (assembly != null)
                {
                    RespondResource(response, assembly, WoopsaConst.UrlSeparator + pathParts[2]);
                }
                else
                {
                    response.WriteError(HTTPStatusCode.NotFound,
                                        string.Format("Assembly not Found at '{0}'", subRoute));
                }
            }
        }
Esempio n. 7
0
        public void HandleRequest(HTTPRequest request, HTTPResponse response)
        {
            if (request.Subroute == "")
            {
                //If there really is no file requested, then we send a 404!
                response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                return;
            }

            //Find the requested file
            string requestedFile = _baseDirectory + request.Subroute.Replace(WoopsaConst.UrlSeparator, Path.DirectorySeparatorChar);

            if (!IsFileAllowed(requestedFile))
            {
                response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                return;
            }

            //Does this file exist?
            if (File.Exists(requestedFile))
            {
                ServeFile(requestedFile, response);
            }
            else if (Directory.Exists(requestedFile))
            {
                //Try to find the index.html file
                requestedFile = requestedFile + "index.html";
                if (File.Exists(requestedFile))
                {
                    ServeFile(requestedFile, response);
                }
                else
                {
                    response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                }
            }
            else
            {
                response.WriteError(HTTPStatusCode.NotFound, "Not Found");
            }
        }
        public void HandleRequest(HTTPRequest request, HTTPResponse response)
        {
            if (request.Subroute == "")
            {
                //If there really is no file requested, then we send a 404!
                response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                return;
            }

            //Find the requested file
            string requestedFile = _baseDirectory + request.Subroute.Replace(WoopsaConst.UrlSeparator, Path.DirectorySeparatorChar);

            if (!IsFileAllowed(requestedFile))
            {
                response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                return;
            }

            //Does this file exist?
            if (File.Exists(requestedFile))
            {
                ServeFile(requestedFile, response);
            }
            else if (Directory.Exists(requestedFile))
            {
                //Try to find the index.html file
                requestedFile = requestedFile + "index.html";
                if (File.Exists(requestedFile))
                {
                    ServeFile(requestedFile, response);
                }
                else
                {
                    response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                }
            }
            else
            {
                response.WriteError(HTTPStatusCode.NotFound, "Not Found");
            }
        }
 public void HandleRequest(HTTPRequest request, HTTPResponse response)
 {
     string subRoute = request.Subroute;
     if (_assembly != null)
         RespondResource(response, _assembly, subRoute);
     else
     {
         Assembly assembly;
         // First element = initial /
         string[] pathParts = subRoute.Split(new char[] { WoopsaConst.UrlSeparator }, 3);
         if (pathParts.Length == 3 && pathParts[1] != "")
             assembly = AssemblyByName(pathParts[1]);
         else
             assembly = null;
         if (assembly != null)
             RespondResource(response, assembly, WoopsaConst.UrlSeparator + pathParts[2]);
         else
             response.WriteError(HTTPStatusCode.NotFound,
                 string.Format("Assembly not Found at '{0}'", subRoute));
     }
 }
 private void RespondResource(HTTPResponse response, Assembly assembly, string subRoute)
 {
     if (subRoute != "")
     {
         string requestedFile = ResourcePath(subRoute);
         if (_baseDirectory != "")
             if (requestedFile != "")
                 requestedFile = _baseDirectory + ResourcePathSeparator + requestedFile;
             else
                 requestedFile = _baseDirectory;
         // Does this resource exist?
         if (!ServeEmbeddedResource(response, assembly, requestedFile))
         {
             string indexHtmlFileResource = requestedFile + ResourcePathSeparator + "index.html";
             //Try to get 'index.html', maybe?
             if (!ServeEmbeddedResource(response, assembly, indexHtmlFileResource))
                 response.WriteError(HTTPStatusCode.NotFound,
                     string.Format("Resource not Found at '{0}'", subRoute));
         }
     }
     else
         //If there really is no file requested, then we send a 404!
         response.WriteError(HTTPStatusCode.NotFound,
             string.Format("Resource not Found at '{0}'", subRoute));
 }
Esempio n. 11
0
        private void HandleClient(TcpClient client)
        {
            lock (_openTcpClients)
                _openTcpClients.Add(client);
            try
            {
                Stream stream = client.GetStream();
                try
                {
                    foreach (PreRouteProcessor processor in PreRouteProcessors)
                    {
                        stream = processor.ProcessStream(stream);
                    }
                    bool         leaveOpen = true;
                    HTTPResponse response  = null;
                    HTTPRequest  request   = null;
                    StreamReader reader    = new StreamReader(stream, Encoding.UTF8, false, 4096);
                    try
                    {
                        while (leaveOpen && !_aborted)
                        {
                            response = new HTTPResponse();

                            /*
                             * Parse the first line of the HTTP Request
                             * Examples:
                             *      GET / HTTP/1.1
                             *      POST /submit HTTP/1.1
                             */
                            string requestString;
                            try
                            {
                                requestString = reader.ReadLine();
                            }
                            catch (Exception)
                            {
                                requestString = null;
                                leaveOpen     = false;
                                break;
                            }
                            if (requestString == null)
                            {
                                break;
                            }

                            string[] parts = requestString.Split(' ');
                            if (parts.Length != 3)
                            {
                                throw new HandlingException(HTTPStatusCode.BadRequest, "Bad Request");
                            }
                            string method  = parts[0].ToUpper();
                            string url     = parts[1];
                            string version = parts[2].ToUpper();

                            //Check if the version is what we expect
                            if (version != "HTTP/1.1" && version != "HTTP/1.0")
                            {
                                throw new HandlingException(HTTPStatusCode.HttpVersionNotSupported, "HTTP Version Not Supported");
                            }

                            //Check if the method is supported
                            if (!_supportedMethods.ContainsKey(method))
                            {
                                throw new HandlingException(HTTPStatusCode.NotImplemented, method + " Method Not Implemented");
                            }
                            HTTPMethod httpMethod = _supportedMethods[method];

                            url = HttpUtility.UrlDecode(url);

                            //Build the request object
                            request = new HTTPRequest(httpMethod, url);

                            //Add all headers to the request object
                            FillHeaders(request, reader);

                            //Handle encoding for this request
                            Encoding clientEncoding = InferEncoding(request);

                            //Extract all the data from the URL (base and query)
                            ExtractQuery(request, clientEncoding);

                            //Extract and decode all the POST data
                            ExtractPOST(request, reader, clientEncoding);

                            bool keepAlive = false;
                            // According to spec, Keep-Alive is ON by default
                            if (version == "HTTP/1.1")
                            {
                                keepAlive = true;
                            }
                            if (request.Headers.ContainsKey(HTTPHeader.Connection))
                            {
                                if (request.Headers[HTTPHeader.Connection].ToLower().Equals("close"))
                                {
                                    keepAlive = false;
                                    response.SetHeader(HTTPHeader.Connection, "close");
                                }
                            }

                            //Keep-Alive can only work on a multithreaded server!
                            if (!keepAlive || !MultiThreaded)
                            {
                                leaveOpen = false;
                                response.SetHeader(HTTPHeader.Connection, "close");
                            }
                            //Pass this on to the route solver
                            OnLog(request, null);
                            Routes.HandleRequest(request, response, stream);
                            OnLog(request, response);
                        }
                    }
                    catch (HandlingException e)
                    {
                        if (response != null)
                        {
                            try
                            {
                                // try to return the response
                                response.WriteError(e.Status, e.ErrorMessage);
                                response.Respond(stream);
                            }
                            catch
                            {
                                // ignore silently if it is not posible
                            }
                            OnLog(request, response);
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        // Do nothing, server is terminating
                    }
                    catch (Exception e)
                    {
                        if (response != null)
                        {
                            try
                            {
                                // try to return the response
                                response.WriteError(HTTPStatusCode.InternalServerError, "Internal Server Error. " + e.Message);
                                response.Respond(stream);
                            }
                            catch
                            {
                                // ignore silently if it is not posible
                            }
                            OnLog(request, response);
                        }
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
                finally
                {
                    stream.Dispose();
                }
            }
            finally
            {
                lock (_openTcpClients)
                    _openTcpClients.Remove(client);
            }
        }
Esempio n. 12
0
        private void HandleClient(TcpClient client)
        {
            lock (_openTcpClients)
                _openTcpClients.Add(client);
            try
            {
                Stream stream = client.GetStream();
                try
                {
                    foreach (PreRouteProcessor processor in PreRouteProcessors)
                    {
                        stream = processor.ProcessStream(stream);
                    }
                    bool leaveOpen = true;
                    HTTPResponse response = null;
                    HTTPRequest request = null;
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 4096);
                    try
                    {
                        while (leaveOpen && !_aborted)
                        {
                            response = new HTTPResponse();
                            /*
                                * Parse the first line of the HTTP Request
                                * Examples:
                                *      GET / HTTP/1.1
                                *      POST /submit HTTP/1.1
                                */
                            string requestString;
                            try
                            {
                                requestString = reader.ReadLine();
                            }
                            catch (Exception)
                            {
                                requestString = null;
                                leaveOpen = false;
                                break;
                            }
                            if (requestString == null)
                                break;

                            string[] parts = requestString.Split(' ');
                            if (parts.Length != 3)
                            {
                                throw new HandlingException(HTTPStatusCode.BadRequest, "Bad Request");
                            }
                            string method = parts[0].ToUpper();
                            string url = parts[1];
                            string version = parts[2].ToUpper();

                            //Check if the version is what we expect
                            if (version != "HTTP/1.1" && version != "HTTP/1.0")
                            {
                                throw new HandlingException(HTTPStatusCode.HttpVersionNotSupported, "HTTP Version Not Supported");
                            }

                            //Check if the method is supported
                            if (!_supportedMethods.ContainsKey(method))
                            {
                                throw new HandlingException(HTTPStatusCode.NotImplemented, method + " Method Not Implemented");
                            }
                            HTTPMethod httpMethod = _supportedMethods[method];

                            url = HttpUtility.UrlDecode(url);

                            //Build the request object
                            request = new HTTPRequest(httpMethod, url);

                            //Add all headers to the request object
                            FillHeaders(request, reader);

                            //Handle encoding for this request
                            Encoding clientEncoding = InferEncoding(request);

                            //Extract all the data from the URL (base and query)
                            ExtractQuery(request, clientEncoding);

                            //Extract and decode all the POST data
                            ExtractPOST(request, reader, clientEncoding);

                            bool keepAlive = false;
                            // According to spec, Keep-Alive is ON by default
                            if (version == "HTTP/1.1")
                                keepAlive = true;
                            if (request.Headers.ContainsKey(HTTPHeader.Connection))
                            {
                                if (request.Headers[HTTPHeader.Connection].ToLower().Equals("close"))
                                {
                                    keepAlive = false;
                                    response.SetHeader(HTTPHeader.Connection, "close");
                                }
                            }

                            //Keep-Alive can only work on a multithreaded server!
                            if (!keepAlive || !MultiThreaded)
                            {
                                leaveOpen = false;
                                response.SetHeader(HTTPHeader.Connection, "close");
                            }
                            //Pass this on to the route solver
                            OnLog(request, null);
                            Routes.HandleRequest(request, response, stream);
                            OnLog(request, response);
                        }
                    }
                    catch (HandlingException e)
                    {
                        if (response != null)
                        {
                            try
                            {
                                // try to return the response
                                response.WriteError(e.Status, e.ErrorMessage);
                                response.Respond(stream);
                            }
                            catch
                            {
                                // ignore silently if it is not posible
                            }
                            OnLog(request, response);
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        // Do nothing, server is terminating
                    }
                    catch (Exception e)
                    {
                        if (response != null)
                        {
                            try
                            {
                                // try to return the response
                                response.WriteError(HTTPStatusCode.InternalServerError, "Internal Server Error. " + e.Message);
                                response.Respond(stream);
                            }
                            catch
                            {
                                // ignore silently if it is not posible
                            }
                            OnLog(request, response);
                        }
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
                finally
                {
                    stream.Dispose();
                }
            }
            finally
            {
                lock (_openTcpClients)
                    _openTcpClients.Remove(client);
            }
        }
Esempio n. 13
0
        private void HandleRequest(WoopsaVerb verb, HTTPRequest request, HTTPResponse response)
        {
            try
            {
                _currentWoopsaServer = this;
                try
                {
                    string result = null;
                    ExecuteBeforeWoopsaModelAccess();
                    try
                    {
                        switch (verb)
                        {
                        case WoopsaVerb.Meta:
                            result = GetMetadata(request.Subroute);
                            break;

                        case WoopsaVerb.Read:
                            result = ReadValue(request.Subroute);
                            break;

                        case WoopsaVerb.Write:
                            result = WriteValue(request.Subroute, request.Body["value"]);
                            break;

                        case WoopsaVerb.Invoke:
                            result = InvokeMethod(request.Subroute, request.Body);
                            break;
                        }
                    }
                    finally
                    {
                        ExecuteAfterWoopsaModelAccess();
                    }
                    response.SetHeader(HTTPHeader.ContentType, MIMETypes.Application.JSON);
                    if (result != null)
                    {
                        response.WriteString(result);
                    }
                }
                finally
                {
                    _currentWoopsaServer = null;
                }
            }
            catch (WoopsaNotFoundException e)
            {
                response.WriteError(HTTPStatusCode.NotFound, e.GetFullMessage(), e.Serialize(), MIMETypes.Application.JSON);
                OnHandledException(e);
            }
            catch (WoopsaInvalidOperationException e)
            {
                response.WriteError(HTTPStatusCode.BadRequest, e.GetFullMessage(), e.Serialize(), MIMETypes.Application.JSON);
                OnHandledException(e);
            }
            catch (WoopsaException e)
            {
                response.WriteError(HTTPStatusCode.InternalServerError, e.GetFullMessage(), e.Serialize(), MIMETypes.Application.JSON);
                OnHandledException(e);
            }
            catch (Exception e)
            {
                response.WriteError(HTTPStatusCode.InternalServerError, e.GetFullMessage(), e.Serialize(), MIMETypes.Application.JSON);
                OnHandledException(e);
            }
        }
Esempio n. 14
0
        internal void HandleRequest(HTTPRequest request, HTTPResponse response, Stream stream)
        {
            try
            {
                bool matchFound = false;
                RouteMapper mapper = null;
                int i = 0;

                for (;;)
                {
                    lock (_routes)
                    {
                        if (i < _routes.Count)
                            mapper = _routes[i++];
                        else
                            break;
                    }
                    string regex = "^" + mapper.Route;
                    if (!mapper.AcceptSubroutes)
                    {
                        regex += "$";
                    }
                    if (Regex.IsMatch(request.BaseURL, regex))
                    {
                        if ((mapper.Methods & request.Method) != 0)
                        {
                            if (mapper.AcceptSubroutes)
                            {
                                int pos = request.BaseURL.IndexOf(mapper.Route);
                                request.Subroute = request.BaseURL.Substring(0, pos) + request.BaseURL.Substring(pos + mapper.Route.Length);
                            }
                            matchFound = true;
                            break;
                        }
                    }
                }

                if (!matchFound)
                {
                    response.WriteError(HTTPStatusCode.NotFound, "Not Found");
                    response.Respond(stream);
                    OnError(RoutingErrorType.NO_MATCHES, "No route found for request", request);
                }
                else
                {
                    mapper.HandleRequest(request, response);
                    response.Respond(stream);
                }
            }
            catch (Exception e)
            {
                response.WriteError(HTTPStatusCode.InternalServerError, String.Format("Internal Server Error {0}", e.Message));
                response.Respond(stream);
                OnError(RoutingErrorType.INTERNAL, "A RouteHandler threw an exception.", request);
            }
        }
Esempio n. 15
0
 private void HandleRequest(WoopsaVerb verb, HTTPRequest request, HTTPResponse response)
 {
     try
     {
         // This is the first thing we do, that way even 404 errors have the right headers
         if (AllowCrossOrigin)
             // TODO: constantes symboliques
             response.SetHeader("Access-Control-Allow-Origin", "*");
         string result = null;
         ExecuteBeforeWoopsaModelAccess();
         try
         {
             switch (verb)
             {
                 case WoopsaVerb.Meta:
                     result = GetMetadata(request.Subroute);
                     break;
                 case WoopsaVerb.Read:
                     result = ReadValue(request.Subroute);
                     break;
                 case WoopsaVerb.Write:
                     result = WriteValue(request.Subroute, request.Body["value"]);
                     break;
                 case WoopsaVerb.Invoke:
                     result = InvokeMethod(request.Subroute, request.Body);
                     break;
             }
         }
         finally
         {
             ExecuteAfterWoopsaModelAccess();
         }
         response.SetHeader(HTTPHeader.ContentType, MIMETypes.Application.JSON);
         if (result != null)
             response.WriteString(result);
     }
     catch (WoopsaNotFoundException e)
     {
         response.WriteError(HTTPStatusCode.NotFound, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
     }
     catch (WoopsaInvalidOperationException e)
     {
         response.WriteError(HTTPStatusCode.BadRequest, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
     }
     catch (WoopsaException e)
     {
         response.WriteError(HTTPStatusCode.InternalServerError, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
     }
     catch (Exception e)
     {
         response.WriteError(HTTPStatusCode.InternalServerError, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
     }
 }
Esempio n. 16
0
 public bool Process(HTTPRequest request, HTTPResponse response)
 {
     bool authenticated;
     _currentUserName = null;
     if (request.Headers.ContainsKey(HTTPHeader.Authorization))
     {
         string authString = request.Headers[HTTPHeader.Authorization].Split(' ')[1];
         authString = Encoding.GetEncoding("ISO-8859-1").GetString(Convert.FromBase64String(authString));
         string[] parts = authString.Split(':');
         string username = parts[0];
         string password = parts[1];
         authenticated = Authenticate(username, password);
         if (authenticated)
             _currentUserName = username;
     }
     else
         authenticated = false;
     if (!authenticated)
     {
         response.SetHeader(HTTPHeader.WWWAuthenticate, "Basic Realm=\"" + Realm + "\"");
         response.WriteError(HTTPStatusCode.Unauthorized, "Unauthorized");
     }
     return authenticated;
 }