Asp.net mvc web api 在项目中的实际应用
前言:以下只是记录本人在项目中的应用,而web api在数据传输方面有多种实现方式,具体可根据实际情况而定!
1:数据传输前的加密,以下用到 微软自带的 Rijndael 类(关于Rijndael 的更多信息请参见MSDN),以下是使用32位密钥加16对称算法密钥向量,代码如下:
//简单定义一个实体类:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://webapi.test.com");
//模拟传输数据:
User entity = new User()
{
Id = 1,
Age = 2,
Name = "hello"
};
string jsonStr = JsonConvert.SerializeObject(entity);
//对数据进行加密:
Rijndael r = Rijndael.Create();
//初始化16位秘钥向量:
r.IV = Encoding.UTF8.GetBytes("快乐加快乐,");
//32位秘钥向量:
string key = "070417fa0e95458684116314a2c7cf18"; //Guid.NewGuid().ToString().Replace("-", "");
r.Key = Encoding.UTF8.GetBytes(key);
byte[] es = new byte[] { };
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(ms, r.CreateEncryptor(), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cStream))
{
sw.WriteLine(jsonStr);
}
}
es = ms.ToArray();
}
2:利用httpclient传输数据,代码如下:
//推送数据:
ByteArrayContent content = new ByteArrayContent(es);
Task.Factory.StartNew(() =>
{
//requestURL根据实际配置的路由决定:
var res = client.PostAsync("webapi/GetData", content).Result;
});
return View();
3:接收httpclient推送的数据并进行解密,代码如下:
[HttpPost]
public async Task<string> GetData()
{
byte[] buffer = await Request.Content.ReadAsByteArrayAsync();
//解密:
Rijndael dr = Rijndael.Create();
//初始化16位秘钥向量:
string key = "070417fa0e95458684116314a2c7cf18";
dr.IV = Encoding.UTF8.GetBytes("快乐加快乐,");
//32位秘钥:
dr.Key = Encoding.UTF8.GetBytes(key);
string dstr = string.Empty;
using (MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length))
{
using (CryptoStream cStream = new CryptoStream(ms, dr.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cStream))
{
dstr = sr.ReadLine();
}
}
}
//解密成功后反序列化数据:
User model = JsonConvert.DeserializeObject<User>(dstr);
//........其它处理
return "ok";
}