国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

WebApi增刪改查Demo

2019-11-17 02:04:04
字體:
來源:轉載
供稿:網友

WebApi增刪改查Demo

1.新建webapi項目

2.配置WebApiConfig

public const string DEFAULT_ROUTE_NAME = "MyDefaultRoute";        public static void Register(HttpConfiguration config)        {            config.Routes.MapHttPRoute(                name: DEFAULT_ROUTE_NAME,                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );            // 取消注釋下面的代碼行可對具有 IQueryable 或 IQueryable<T> 返回類型的操作啟用查詢支持。            // 若要避免處理意外查詢或惡意查詢,請使用 QueryableAttribute 上的驗證設置來驗證傳入查詢。            // 有關詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkId=279712。            //config.EnableQuerySupport();            // 若要在應用程序中禁用跟蹤,請注釋掉或刪除以下代碼行            // 有關詳細信息,請參閱: http://www.asp.net/web-api            config.EnableSystemDiagnosticsTracing();        }

3.在models文件新建person模型

public class Person    {        public int Id { get; set; }        public string FirstName { get; set; }        public string LastName { get; set; }    }

4.在models文件中添加ipersonRepository

interface IPersonRepository    {        IEnumerable<Person> GetAll();        Person Get(int id);        Person Add(Person person);        void Remove(int id);        bool Update(Person person);    }

5.在models文件中添加倉庫實現

public class PersonRepository : IPersonRepository    {        // We are using the list and _fakeDatabaseID to represent what would        // most likely be a database of some sort, with an auto-incrementing ID field:        private List<Person> _people = new List<Person>();        private int _fakeDatabaseID = 1;        public PersonRepository()        {            // For the moment, we will load some sample data during initialization.             this.Add(new Person { LastName = "Lennon", FirstName = "John" });            this.Add(new Person { LastName = "McCartney", FirstName = "Paul" });            this.Add(new Person { LastName = "Harrison", FirstName = "George" });            this.Add(new Person { LastName = "Starr", FirstName = "Ringo" });        }        public IEnumerable<Person> GetAll()        {            return _people;        }        public Person Get(int id)        {            return _people.Find(p => p.Id == id);        }        public Person Add(Person person)        {            if (person == null)            {                throw new ArgumentNullException("person");            }            person.Id = _fakeDatabaseID++;            _people.Add(person);            return person;        }        public void Remove(int id)        {            _people.RemoveAll(p => p.Id == id);        }        public bool Update(Person person)        {            if (person == null)            {                throw new ArgumentNullException("person");            }            int index = _people.FindIndex(p => p.Id == person.Id);            if (index == -1)            {                return false;            }            _people.RemoveAt(index);            _people.Add(person);            return true;        }    }

6.在controllers中添加apiController為PersonController

public class PersonController : ApiController    {        static readonly IPersonRepository databasePlaceholder = new PersonRepository();        public IEnumerable<Person> GetAllPeople()        {            return databasePlaceholder.GetAll();        }        public Person GetPersonByID(int id)        {            Person person = databasePlaceholder.Get(id);            if (person == null)            {                throw new HttpResponseException(HttpStatusCode.NotFound);            }            return person;        }        public HttpResponseMessage PostPerson(Person person)        {            person = databasePlaceholder.Add(person);            string apiName = WebApi.WebApiConfig.DEFAULT_ROUTE_NAME;            var response =                this.Request.CreateResponse<Person>(HttpStatusCode.Created, person);            string uri = Url.Link(apiName, new { id = person.Id });            response.Headers.Location = new Uri(uri);            return response;        }        public bool PutPerson(Person person)        {            if (!databasePlaceholder.Update(person))            {                throw new HttpResponseException(HttpStatusCode.NotFound);            }            return true;        }        public void DeletePerson(int id)        {            Person person = databasePlaceholder.Get(id);            if (person == null)            {                throw new HttpResponseException(HttpStatusCode.NotFound);            }            databasePlaceholder.Remove(id);        }    }

以上就完成了webapi的簡單搭建。接下來創建客戶端來訪問webapi。

7.新建console項目,添加webapi Core Library。

添加引用

using System.Net.Http; using Newtonsoft.Json.Linq;

private const string url = "http://localhost:43571/";        static void Main(string[] args)        {            Console.WriteLine("Retreive All The People:");            JArray people = GetAllPerson();             foreach (var person in people)            {                Console.WriteLine(person);            }            // WRITE A SPECIFIC PERSON TO CONSOLE (JSON):            Console.WriteLine(Environment.NewLine + "Retreive a Person by ID:");            JObject singlePerson = GetPerson(2);            Console.WriteLine(singlePerson);            // ADD NEW PERSON, THEN WRITE TO CONSOLE (JSON):            Console.WriteLine(Environment.NewLine + "Add a new Person and return the new object:");            JObject newPerson = AddPerson("Atten", "John");            Console.WriteLine(newPerson);            // UPDATE AN EXISTING PERSON, THEN WRITE TO CONSOLE (JSON):            Console.WriteLine(Environment.NewLine + "Update an existing Person and return a boolean:");            // Pretend we already had a person's data:            JObject personToUpdate = GetPerson(2);            string newLastName = "Richards";            Console.WriteLine("Update Last Name of " + personToUpdate + "to " + newLastName);            // Pretend we don't already know the Id:            int id = personToUpdate.Value<int>("Id");            string FirstName = personToUpdate.Value<string>("FirstName");            string LastName = personToUpdate.Value<string>("LastName");            if (UpdatePerson(id, newLastName, FirstName))            {                Console.WriteLine(Environment.NewLine + "Updated person:");                Console.WriteLine(GetPerson(id));            }            // DELETE AN EXISTING PERSON BY ID:            Console.WriteLine(Environment.NewLine + "Delete person object:");            DeletePerson(5);            // WRITE THE UPDATED LIST TO THE CONSOLE:            {                // WRITE ALL PEOPLE TO CONSOLE                Console.WriteLine("Retreive All The People using classes:");                people = GetAllPerson();                foreach (var person in people)                {                    Console.WriteLine(person);                }            }            Console.Read();        }        /// <summary>        /// get all Person        /// </summary>        /// <returns></returns>        static JArray GetAllPerson()        {            HttpClient client = new HttpClient();            HttpResponseMessage response = client.GetAsync(url + "api/person").Result;            return response.Content.ReadAsAsync<JArray>().Result;        }        static JObject GetPerson(int id)        {            HttpClient client = new HttpClient();            HttpResponseMessage response = client.GetAsync(url + "api/person/" + id).Result;            return response.Content.ReadAsAsync<JObject>().Result;        }        static JObject AddPerson(string newLastName, string newFirstName)        {            var newPerson = new { LastName
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 福清市| 舒城县| 辽阳市| 华阴市| 西贡区| 雷山县| 松溪县| 兴文县| 龙泉市| 微山县| 平远县| 炉霍县| 九龙城区| 洮南市| 涟水县| 青阳县| 察哈| 临海市| 竹山县| 萨迦县| 雅江县| 屏边| 广南县| 武乡县| 柘城县| 香格里拉县| 邹平县| 临颍县| 华池县| 海城市| 霍邱县| 青岛市| 明星| 清原| 山东省| 赫章县| 高清| 湟源县| 绵阳市| 景东| 蓝田县|