WebApi 的CRUD 的方法的应用

2021-09-21 10:14

阅读:1047

标签:oid   reg   控制台应用程序   浏览器   lin   中国   eth   .config   edm   一.最近一直在忙于开发公司的新的项目和搭建公司的框架,也好久没有写博客了。对于RaidDevelopmentFramework 我有着自己的见解在应用到实际的框架中确实挺好用的,但是还是存在一部分的问题。这个需要后期进行不断的完善以及修改。最近一段时间对于这个WebApi 我又进行重新的研究和学习。 ASP.NET Web API是用于构建可以从任何客户机访问(包括浏览器和移动设备)的HTTP服务的框架。 它是一种基于.NET Framework构建RESTFUL应用程序的理想平台。 二.那么WebApi 如何在传统的应用程序中进行使用和结合到.NET FrameWork 来进行使用。 三.ASP.NET Web API特性 Web API 是一个构建基于restful服务的理想平台。 Web API 是基于Asp.Net,支持ASP.Net 请求/响应管道 Web API 有良好的路由机制。 Web API 支持不同格式的响应数据,内置支持JSON、XML BSON格式。 Web API 可以部署非常方便。 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 /// 43 /// 获取列表的信息 44 /// 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(); 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(jsonData); 65 foreach (var items in customerList.ToList()) 66 { 67 Console.WriteLine("用户名:" + items.ContactName + "公司名称:" + items.CompanyName); 68 } 69 } 70 } 71 } 72 73 /// 74 ///获取单个的数据的信息 75 /// 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().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(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 /// 99 ///进行更新数据 100 /// 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() 119 { 120 {"ContactName","张三"}, 121 {"Phone","***"}, 122 {"Address","江苏南京"}, 123 {"Country","中国"}, 124 {"CompanyName","江苏**"} 125 }); 126 127 //两种方式的返回的结果是一致的。但是对于其中的传输的方式确实不一致的。 128 var response = await httpClient.PutAsync(@"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().Result; 132 var jsonData = response.Content.ReadAsStringAsync().Result; 133 var json = await response.Content.ReadAsStringAsync(); 134 //将返回的JSON 数据进行反序列化成为对象 135 var customerData = JsonConvert.DeserializeObject(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 /// 156 ///根据ID进行删除的操作 157 /// 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 /// 169 /// 添加客户的信息 170 /// 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(@"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().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 的方法的应用标签:oid   reg   控制台应用程序   浏览器   lin   中国   eth   .config   edm   原文地址:http://www.cnblogs.com/LowKeyCXY/p/7401762.html


评论


亲,登录后才可以留言!