CRUD Operation using Web API and Windows Application ╰+攻爆jí腚メ 2022-08-06 06:30 21阅读 0赞 原文:[http://www.dotnetfunda.com/articles/show/2341/crud-operation-using-web-api-and-windows-application][http_www.dotnetfunda.com_articles_show_2341_crud-operation-using-web-api-and-windows-application] ## Introduction ## In this article we will perform a basic CRUD operation using Web API and Windows Application ## Straight to Experiment ## Fire up visual studio and choose "ASP.NET MVC 4 Web Application" ![Niladri.Biswas_7216_1.png][] Next choose "Web API" and let the view engine be "Razor".Click "OK" ![Niladri.Biswas_8974_2.png][] Add an Product Model (Product.cs) in the Models Folder public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } Add an Interface IProductRepository.cs as under interface IProductRepository { IEnumerable GetAll(); Product Get(int id); Product Add(Product item); bool Update(Product item); bool Delete(int id); } Add a concrete ProductRepository.cs as under public class ProductRepository : IProductRepository { private List<Product> products = new List<Product>(); private int _nextId = 1; public ProductRepository() { Add(new Product { Name = "Floppy Disk", Category = "Hardware/Electronics", Price = 20.10M }); Add(new Product { Name = "BMW", Category = "Car", Price = 3400000 }); } public IEnumerable<Product> GetAll() { return products; } public Product Get(int id) { return products.Find(p => p.Id == id); } public Product Add(Product item) { item.Id = _nextId++; products.Add(item); return item; } public bool Update(Product item) { int index = products.FindIndex(p => p.Id == item.Id); products.RemoveAt(index); products.Insert(index, item); return true; } public bool Delete(int id) { products.RemoveAll(p => p.Id == id); return true; } } Run the application Now create a windows application and make a UI screen as under ![Niladri.Biswas_1025_3.png][] For obtaining all the product, let us write the below code private async void GetAllProducts() { using (var client = new HttpClient()) { using (var response = await client.GetAsync(URI)) { if (response.IsSuccessStatusCode) { var productJsonString = await response.Content.ReadAsStringAsync(); dataGridView1.DataSource = JsonConvert.DeserializeObject<Product[]>(productJsonString).ToList(); } } } } First of all we are creating an instance of the HttpClient. Then by using the "GetAsync" we are sending a GET request to the specified Uri as an asynchronous operation. By using the "ReadAsStringAsync" method, we are writing the HTTP content to a string as an asynchronous operation. The JsonConvert.DeserializeObject will convert the JSon string to the specified dotnet type.For this to use we need to download the [JSON.net][] library.And then add the "Newtonsoft.Json.dll" specific to the dotnet version. Finally we are binding the result to the grid ![Niladri.Biswas_2782_4.png][] For inserting a product, let us write the below code private async void AddProduct() { Product p = new Product(); p.Id = 3; p.Name = "Rolex"; p.Category = "Watch"; p.Price = 1299936; using (var client = new HttpClient()) { var serializedProduct = JsonConvert.SerializeObject(p); var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json"); var result = await client.PostAsync(URI, content); } GetAllProducts(); } First of all we are creating the product object and adding a product to it.Then serializing the product to the JSon string by using the "JsonConvert.SerializeObject" method. Finally we are using the "PostAsync" method for sending a POST request to the specified Uri as an asynchronous operation. And invoking the "GetAllProducts()" to show the new collection. ![Niladri.Biswas_6396_5.png][] The update method implementation is as under private async void UpdateProduct() { Product p = new Product(); p.Id = 3; p.Name = "Rolex"; p.Category = "Watch"; p.Price = 1400000; //changed the price using (var client = new HttpClient()) { var serializedProduct = JsonConvert.SerializeObject(p); var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json"); var result = await client.PutAsync(String.Format("{0}/{1}", URI, p.Id), content); } GetAllProducts(); } The implementation is very similar to the Insert methid except that we are using "PutAsync" that will send a PUT request to the specified Uri as an asynchronous operation. ![Niladri.Biswas_9618_6.png][] And finally comes the Delete method whose implementation is as under private async void DeleteProduct() { using (var client = new HttpClient()) { var result = await client.DeleteAsync(String.Format("{0}/{1}", URI, 3)); } GetAllProducts(); } We are passing the id(which is 3 in this case) to the "DeleteAsync" method that will send a DELETE request to the specified Uri as an asynchronous operation. ![Niladri.Biswas_0497_7.png][] ## Conclusion ## Hope this will be helpful.Thanks for reading.Zipped file is attached herewith. [http_www.dotnetfunda.com_articles_show_2341_crud-operation-using-web-api-and-windows-application]: http://www.dotnetfunda.com/articles/show/2341/crud-operation-using-web-api-and-windows-application [Niladri.Biswas_7216_1.png]: /images/20220806/18a5aabc933b436c94146db4562e1c5c.png [Niladri.Biswas_8974_2.png]: /images/20220806/f8f295935d7d4469920bcbbecb037ba4.png [Niladri.Biswas_1025_3.png]: /images/20220806/9d0019dbd5c04fd4a1ed25acdbaf929d.png [JSON.net]: http://james.newtonking.com/projects/json-net.aspx [Niladri.Biswas_2782_4.png]: /images/20220806/170e24fc87b8466b9e4043b935328736.png [Niladri.Biswas_6396_5.png]: /images/20220806/c7b87736dc344c00ac58d9012d029b64.png [Niladri.Biswas_9618_6.png]: /images/20220806/fc8783edc8b74397befb31d48af20f2b.png [Niladri.Biswas_0497_7.png]: /images/20220806/c18d487bae9c41988ae2d99437e25d31.png
还没有评论,来说两句吧...