WebApi 的CRUD 的方法的应用

时间:2022-05-27 23:06:32

一.最近一直在忙于开发公司的新的项目和搭建公司的框架,也好久没有写博客了。对于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 的方法使用来进行说明。

 #region 使用客户端进行调用WebApi来进行实现
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Hosting;
using System.Net.Http.Formatting;
using System.Net.Http;
using System.Net;
using WebAPI.Models;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.IO; namespace ConsoleClient
{
class Program
{ private readonly static JsonMediaTypeFormatter formatter =
GlobalConfiguration.Configuration.Formatters
.Where(f =>
{
return f.SupportedMediaTypes.Any
(v => v.MediaType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase));
})
.FirstOrDefault() as JsonMediaTypeFormatter;
static void Main(string[] args)
{
//GetAll();
//GetFristMessage();
//Update();
//Delete();
Console.WriteLine(DecryptDES("zqindFI5UNSKrp5weiuIm5cScBM=", "Y+Z7bE1/DoLCWxchX9eeyg=="));
//AddCustomerMessage();
Console.ReadLine();
} /// <summary>
/// 获取列表的信息
/// </summary>
private static async void GetAll()
{
HttpClient _httpClient = new HttpClient();
string _url = string.Format(@"http://localhost:3536/api/Customers");
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
var data = await _httpClient.GetAsync(_url);
using (var httpClient = new HttpClient(handler))
{
var response = await data.Content.ReadAsAsync<List<Customers>>();
var responseModel = await httpClient.GetAsync(_url);
if (responseModel.IsSuccessStatusCode == true)
{
foreach (var items in response.ToList())
{
Console.WriteLine("用户名:" + items.ContactName + "公司名称:" + items.CompanyName);
}
Console.WriteLine("==============================================");
var jsonData = await responseModel.Content.ReadAsStringAsync();
Console.WriteLine(jsonData);
var customerList = JsonConvert.DeserializeObject<List<Customers>>(jsonData);
foreach (var items in customerList.ToList())
{
Console.WriteLine("用户名:" + items.ContactName + "公司名称:" + items.CompanyName);
}
}
}
} /// <summary>
///获取单个的数据的信息
/// </summary>
private static async void GetFristMessage()
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var httpClient = new HttpClient(handler))
{
var response = await httpClient.GetAsync(@"http://localhost:3536/api/Customers/Get?id=2"); var customer = response.Content.ReadAsAsync<Customers>().Result;
var jsonData = response.Content.ReadAsStringAsync().Result;//将其转化为JSON
var json = await response.Content.ReadAsStringAsync(); //调用此方法将其转化为JSON效果和上面一样
Console.WriteLine(json);
var customerModel = JsonConvert.DeserializeObject<Customers>(await response.Content.ReadAsStringAsync());
if (response.IsSuccessStatusCode == true)
{
Console.WriteLine("用户名称:" + customerModel.ContactName + "公司名称:" + customerModel.CompanyName);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.RequestMessage);
Console.WriteLine("用户名称:" + customer.ContactName + "公司名称:" + customer.CompanyName);
}
}
} /// <summary>
///进行更新数据
/// </summary>
private static async void Update()
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; using (var httpClient = new HttpClient(handler))
{
try
{
Customers customer = new Customers();
customer.Address = "江苏";
customer.City = "南京";
customer.CompanyName = "南京***有限公司";
customer.Country = "中国";
customer.CustomerID = ;
customer.Phone = "****";
customer.ContactName = "李四"; var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"ContactName","张三"},
{"Phone","***"},
{"Address","江苏南京"},
{"Country","中国"},
{"CompanyName","江苏**"}
}); //两种方式的返回的结果是一致的。但是对于其中的传输的方式确实不一致的。
var response = await httpClient.PutAsync<Customers>(@"http://localhost:3536/api/Customers/Get?id=123", customer, formatter);
//var response = await httpClient.PutAsync(@"http://localhost:3536/api/Customers/Get?id=123",content); var customerModel = response.Content.ReadAsAsync<Customers>().Result;
var jsonData = response.Content.ReadAsStringAsync().Result;
var json = await response.Content.ReadAsStringAsync();
//将返回的JSON 数据进行反序列化成为对象
var customerData = JsonConvert.DeserializeObject<CustomersModel>(jsonData);
Console.WriteLine(customerData.CompanyName);
Console.WriteLine("=========================================");
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
if (response.IsSuccessStatusCode == true)
{
if (customerModel != null)
{
Console.WriteLine("用户名称:" + customerModel.ContactName + "公司名称:" + customerModel.CompanyName);
}
} }
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
} /// <summary>
///根据ID进行删除的操作
/// </summary>
private static async void Delete()
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var httpClient = new HttpClient(handler))
{
var response =await httpClient.DeleteAsync(@"http://localhost:3536/api/Customers/Delete?id=123");
Console.WriteLine("删除操作的状态码:"+response.StatusCode);
}
} /// <summary>
/// 添加客户的信息
/// </summary>
public static async void AddCustomerMessage()
{
var handler = new HttpClientHandler() {AutomaticDecompression=DecompressionMethods.GZip };
Customers customer = new Customers();
customer.Address = "江苏";
customer.City = "南京";
customer.CompanyName = "南京****";
customer.Country = "中国";
customer.CustomerID = ;
customer.Phone = "***";
customer.ContactName = "赵六";
using (var httpClient=new HttpClient(handler))
{
var response = await httpClient.PostAsync<Customers>(@"http://localhost:3536/api/Customers",customer,formatter);
if (response.IsSuccessStatusCode==true)
{
var data= response.Content.ReadAsStringAsync().Result;
Console.WriteLine(response.Content.ReadAsAsync<Customers>().Result.CompanyName);
}
}
} public static async void Test(string url= "http://localhost:3536/api/Customers", string json="")
{
var handler = new HttpClientHandler() { AutomaticDecompression=DecompressionMethods.GZip};
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType=new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
using (var httpClient=new HttpClient(handler))
{
var response =await httpClient.PostAsync(url, httpContent);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
} public class CustomersModel
{
public int CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
} public static string DecryptDES(string decryptString, string decryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = { 0x13, 0x24, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, , inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return decryptString;
}
} }
}

2017.08-20 22:19:23

以上内容全部是基于原创 如需转载请标明!!!!谢谢合作。