標籤:
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";
}
Asp.net mvc web api 在項目中的實際應用