Exemplo n.º 1
0
        public static void Login(Session session, string username, string password)
        {
            if (session.IsLoggedIn)
            {
                return;
            }

            Consume(session, "api/user/login",
                    (request) =>
            {
                request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                request.AddParameter("name", username);
                request.AddParameter("password", password);
            },
                    (response) =>
            {
                if (response.ErrorException != null)
                {
                    throw response.ErrorException;
                }
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ErrorException(response);
                }

                if (!response.Cookies.Any(x => x.Name == "me"))
                {
                    if (!string.IsNullOrEmpty(response.Content))
                    {
                        LoginFailedResponse lfr = null;
                        try
                        {
                            lfr = new Newtonsoft.Json.JsonSerializer().Deserialize <LoginFailedResponse>(response.Content);
                        } catch
                        {
                            throw new Exception(string.Format("Server returned: \"{0}\"", response.Content));
                        }
                        throw new Exception(lfr.ToString());
                    }
                    throw new Exception("Unexpected response");
                }
            }, Method.POST);
        }