コード例 #1
0
        // GET api/contacts
        public HttpResponseMessage Get()
        {
            List <Contact> list = new List <Contact>();

            try
            {
                var conn    = WebApiConfig.GetMySqlConnection();
                var command = conn.CreateCommand();
                command.CommandText = "SELECT * FROM contacts";
                conn.Open();
                try
                {
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var contact = ContactMapper.GetContactFromReader(reader);
                            list.Add(contact);
                        }
                    }
                }
                catch
                {
                    throw;
                }
            }
            catch
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
            return(Request.CreateResponse(HttpStatusCode.OK, list));
        }
コード例 #2
0
        // GET api/contacts/5
        public HttpResponseMessage Get(int id)
        {
            Contact contact = new Contact();

            try
            {
                var conn    = WebApiConfig.GetMySqlConnection();
                var command = conn.CreateCommand();
                command.CommandText = "SELECT * FROM contacts WHERE id=@id";
                command.Parameters.AddWithValue("@id", id);
                conn.Open();
                try
                {
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            contact = ContactMapper.GetContactFromReader(reader);
                        }
                        else
                        {
                            return(Request.CreateResponse(HttpStatusCode.NotFound));
                        }
                    }
                }
                catch
                {
                    throw;
                }
            }
            catch
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
            return(Request.CreateResponse(HttpStatusCode.OK, contact));
        }