1. 程式人生 > >WebApi 的CRUD 的方法的應用

WebApi 的CRUD 的方法的應用

控制臺 space ont cst 構建 method address pcl stream

一.最近一直在忙於開發公司的新的項目和搭建公司的框架,也好久沒有寫博客了。對於RaidDevelopmentFramework 我有著自己的見解在應用到實際的框架中確實挺好用的,但是還是存在一部分的問題。這個需要後期進行不斷的完善以及修改。最近一段時間對於這個WebApi 我又進行重新的研究和學習。

ASP.NET Web API是用於構建可以從任何客戶機訪問(包括瀏覽器和移動設備)的HTTP服務的框架。 它是一種基於.NET Framework構建RESTFUL應用程序的理想平臺。

二.那麽WebApi 如何在傳統的應用程序中進行使用和結合到.NET FrameWork 來進行使用。

三.ASP.NET Web API特性

  1. Web API 是一個構建基於restful服務的理想平臺。

  2. Web API 是基於Asp.Net,支持ASP.Net 請求/響應管道

  3. Web API 有良好的路由機制。

  4. Web API 支持不同格式的響應數據,內置支持JSON、XML BSON格式。

  5. Web API 可以部署非常方便。

  6. Web API框架包括新的HttpClient,他可以與Web API服務器通信。HttpClient可以在ASP.Net MVC服務器端,Windows Form應用程序,控制臺應用程序或其他應用程序中使用。

四. 關於

ASP.NET Web API版本

web api版本
支持的.net framework版本 對應的MVC版本 支持的VS版本
Web API 1.0 .NET Framework 4.0 ASP.NET MVC 4 VS 2010
Web API 2.0 .NET Framework 4.5 ASP.NET MVC 5 VS 2012,VS 2013


ASP.NET Web API VS WCF

web api wcf
開源,支持.net framework 支持.net framework
只支持HTT通信協議 支持HTTP,TCP,UDP以及自定義通信協議等
良好的路由機制來匹配url與對應接口 基於Attribute來匹配
使用類似於Asp.net MVC的路由規則和Controller模型 使用Service,契約等
不支持可靠的消息傳遞和事務。 支持可靠的消息傳遞和事務。
可以使用HttpConfiguration 來配置Web Api,不一定需要web.config配置 使用web.config和Attribute來配置一個服務
適合構建RESTful服務。 支持構建RESTful服務但有局限性

五. 下面通過進行對於CRUD 的方法使用來進行說明。

  1 #region 使用客戶端進行調用WebApi來進行實現                                       
  2 #endregion
  3 using System;
  4 using System.Collections.Generic;
  5 using System.Linq;
  6 using System.Text;
  7 using System.Threading.Tasks;
  8 using System.Web.Http;
  9 using System.Web.Http.Hosting;
 10 using System.Net.Http.Formatting;
 11 using System.Net.Http;
 12 using System.Net;
 13 using WebAPI.Models;
 14 using Newtonsoft.Json;
 15 using System.Security.Cryptography;
 16 using System.IO;
 17 
 18 namespace ConsoleClient
 19 {
 20     class Program
 21     {
 22 
 23         private readonly static JsonMediaTypeFormatter formatter =
 24         GlobalConfiguration.Configuration.Formatters
 25         .Where(f =>
 26         {
 27             return f.SupportedMediaTypes.Any
 28             (v => v.MediaType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase));
 29         })
 30         .FirstOrDefault() as JsonMediaTypeFormatter;
 31         static void Main(string[] args)
 32         {
 33             //GetAll();
 34             //GetFristMessage();
 35             //Update();
 36             //Delete();
 37             Console.WriteLine(DecryptDES("zqindFI5UNSKrp5weiuIm5cScBM=", "Y+Z7bE1/DoLCWxchX9eeyg=="));
 38             //AddCustomerMessage();
 39             Console.ReadLine();
 40         }
 41 
 42         /// <summary>
 43         /// 獲取列表的信息
 44         /// </summary>
 45         private static async void GetAll()
 46         {
 47             HttpClient _httpClient = new HttpClient();
 48             string _url = string.Format(@"http://localhost:3536/api/Customers");
 49             var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
 50             var data = await _httpClient.GetAsync(_url);
 51             using (var httpClient = new HttpClient(handler))
 52             {
 53                 var response = await data.Content.ReadAsAsync<List<Customers>>();
 54                 var responseModel = await httpClient.GetAsync(_url);
 55                 if (responseModel.IsSuccessStatusCode == true)
 56                 {
 57                     foreach (var items in response.ToList())
 58                     {
 59                         Console.WriteLine("用戶名:" + items.ContactName + "公司名稱:" + items.CompanyName);
 60                     }
 61                     Console.WriteLine("==============================================");
 62                     var jsonData = await responseModel.Content.ReadAsStringAsync();
 63                     Console.WriteLine(jsonData);
 64                     var customerList = JsonConvert.DeserializeObject<List<Customers>>(jsonData);
 65                     foreach (var items in customerList.ToList())
 66                     {
 67                         Console.WriteLine("用戶名:" + items.ContactName + "公司名稱:" + items.CompanyName);
 68                     }
 69                 }
 70             }
 71         }
 72 
 73         /// <summary>
 74         ///獲取單個的數據的信息
 75         /// </summary>
 76         private static async void GetFristMessage()
 77         {
 78             var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
 79             using (var httpClient = new HttpClient(handler))
 80             {
 81                 var response = await httpClient.GetAsync(@"http://localhost:3536/api/Customers/Get?id=2");
 82 
 83                 var customer = response.Content.ReadAsAsync<Customers>().Result;
 84                 var jsonData = response.Content.ReadAsStringAsync().Result;//將其轉化為JSON 
 85                 var json = await response.Content.ReadAsStringAsync(); //調用此方法將其轉化為JSON效果和上面一樣
 86                 Console.WriteLine(json);
 87                 var customerModel = JsonConvert.DeserializeObject<Customers>(await response.Content.ReadAsStringAsync());
 88                 if (response.IsSuccessStatusCode == true)
 89                 {
 90                     Console.WriteLine("用戶名稱:" + customerModel.ContactName + "公司名稱:" + customerModel.CompanyName);
 91                     Console.WriteLine(response.StatusCode);
 92                     Console.WriteLine(response.RequestMessage);
 93                     Console.WriteLine("用戶名稱:" + customer.ContactName + "公司名稱:" + customer.CompanyName);
 94                 }
 95             }
 96         }
 97 
 98         /// <summary>
 99         ///進行更新數據
100         /// </summary>
101         private static async void Update()
102         {
103             var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
104 
105             using (var httpClient = new HttpClient(handler))
106             {
107                 try
108                 {
109                     Customers customer = new Customers();
110                     customer.Address = "江蘇";
111                     customer.City = "南京";
112                     customer.CompanyName = "南京***有限公司";
113                     customer.Country = "中國";
114                     customer.CustomerID = 123;
115                     customer.Phone = "****";
116                     customer.ContactName = "李四";
117 
118                     var content = new FormUrlEncodedContent(new Dictionary<string, string>()
119                     {
120                        {"ContactName","張三"},
121                        {"Phone","***"},
122                        {"Address","江蘇南京"},
123                        {"Country","中國"},
124                        {"CompanyName","江蘇**"}
125                    });
126 
127                     //兩種方式的返回的結果是一致的。但是對於其中的傳輸的方式確實不一致的。
128                     var response = await httpClient.PutAsync<Customers>(@"http://localhost:3536/api/Customers/Get?id=123", customer, formatter);
129                     //var response = await httpClient.PutAsync(@"http://localhost:3536/api/Customers/Get?id=123",content);
130 
131                     var customerModel = response.Content.ReadAsAsync<Customers>().Result;
132                     var jsonData = response.Content.ReadAsStringAsync().Result;
133                     var json = await response.Content.ReadAsStringAsync();
134                     //將返回的JSON 數據進行反序列化成為對象
135                     var customerData = JsonConvert.DeserializeObject<CustomersModel>(jsonData);
136                     Console.WriteLine(customerData.CompanyName);
137                     Console.WriteLine("=========================================");
138                     Console.WriteLine(response.Content.ReadAsStringAsync().Result);
139                     if (response.IsSuccessStatusCode == true)
140                     {
141                         if (customerModel != null)
142                         {
143                             Console.WriteLine("用戶名稱:" + customerModel.ContactName + "公司名稱:" + customerModel.CompanyName);
144                         }
145                     }
146 
147                 }
148                 catch (Exception ex)
149                 {
150                     throw new Exception(ex.ToString());
151                 }
152             }
153         }
154 
155         /// <summary>
156         ///根據ID進行刪除的操作
157         /// </summary>
158         private static async void Delete()
159         {
160             var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
161             using (var httpClient = new HttpClient(handler))
162             {
163                 var response =await httpClient.DeleteAsync(@"http://localhost:3536/api/Customers/Delete?id=123");
164                 Console.WriteLine("刪除操作的狀態碼:"+response.StatusCode);
165             }
166         }
167         
168         /// <summary>
169         /// 添加客戶的信息
170         /// </summary>
171         public static async void AddCustomerMessage()
172         {
173             var handler = new HttpClientHandler() {AutomaticDecompression=DecompressionMethods.GZip };
174             Customers customer = new Customers();
175             customer.Address = "江蘇";
176             customer.City = "南京";
177             customer.CompanyName = "南京****";
178             customer.Country = "中國";
179             customer.CustomerID = 123;
180             customer.Phone = "***";
181             customer.ContactName = "趙六";
182             using (var httpClient=new HttpClient(handler))
183             {
184                 var response = await httpClient.PostAsync<Customers>(@"http://localhost:3536/api/Customers",customer,formatter);
185                 if (response.IsSuccessStatusCode==true)
186                 {
187                     var data=  response.Content.ReadAsStringAsync().Result;
188                     Console.WriteLine(response.Content.ReadAsAsync<Customers>().Result.CompanyName);
189                 }
190             }
191         }
192 
193         public static async void Test(string  url= "http://localhost:3536/api/Customers", string json="")
194         {
195             var handler = new HttpClientHandler() { AutomaticDecompression=DecompressionMethods.GZip};
196             HttpContent httpContent = new StringContent(json);
197             httpContent.Headers.ContentType=new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
198             using (var httpClient=new HttpClient(handler))
199             {
200                 var response =await  httpClient.PostAsync(url, httpContent);
201                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
202             }
203         }
204 
205         public class CustomersModel
206         {
207             public int CustomerID { get; set; }
208             public string CompanyName { get; set; }
209             public string ContactName { get; set; }
210             public string ContactTitle { get; set; }
211             public string Address { get; set; }
212             public string City { get; set; }
213             public string Region { get; set; }
214             public string PostalCode { get; set; }
215             public string Country { get; set; }
216             public string Phone { get; set; }
217             public string Fax { get; set; }
218         }
219 
220          
221         public static string DecryptDES(string decryptString, string decryptKey)
222         {
223             try
224             {
225                 byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
226                 byte[] rgbIV = { 0x13, 0x24, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
227              
228                 byte[] inputByteArray = Convert.FromBase64String(decryptString);
229                 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
230                 MemoryStream mStream = new MemoryStream();
231                 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
232                 cStream.Write(inputByteArray, 0, inputByteArray.Length);
233                 cStream.FlushFinalBlock();
234                 return Encoding.UTF8.GetString(mStream.ToArray());
235             }
236             catch
237             {
238                 return decryptString;
239             }
240         }
241 
242     }
243 }

2017.08-20 22:19:23

以上內容全部是基於原創 如需轉載請標明!!!!謝謝合作。

WebApi 的CRUD 的方法的應用