ASP. NET MVC Web APIPractical Application in the project
Preface: The following is just the application of people in the project, and the Web API in the data transmission has a variety of ways to achieve, depending on the actual situation depends!
1: Encryption before data transfer, the following is used in Microsoft's own Rijndael class ( for more information about Rijndael , see MSDN ), the three-bit key plus The symmetric algorithm initialization vector, the code is as follows:
simply define an entity class:
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");
Analog Transfer data:
User entity = New User ()
{
Id = 1,
Age = 2,
Name = "Hello"
};
String jsonstr = Jsonconvert.serializeobject (entity);
Encrypt the data:
Rijndael r = rijndael.create ();
Initialize the 16-bit key vector:
R.IV = Encoding.UTF8.GetBytes ("Joy accelerates Music,");
32-bit secret key vector:
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: transfer data using HttpClient, the code is as follows:
Push data:
Bytearraycontent content = new Bytearraycontent (es);
Task.Factory.StartNew (() =
{
The Requesturl is determined based on the actual configured route:
var res = client. Postasync ("Webapi/getdata", content). Result;
});
return View ();
3: Receive httpclient push data and decrypt it, the code is as follows:
[HttpPost]
Public async task<string> GetData ()
{
byte[] buffer = await Request.Content.ReadAsByteArrayAsync ();
Decrypt:
Rijndael dr = Rijndael.create ();
Initialize the 16-bit key vector:
string key = "070417fa0e95458684116314a2c7cf18";
DR.IV = Encoding.UTF8.GetBytes ("Joy accelerates Music,");
32-bit secret key:
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 ();
}
}
}
Deserialization data after decryption succeeds:
User model = jsonconvert.deserializeobject<user> (DSTR);
//........ Other processing
return "OK";
}
The application of the ASP. NET MVC Web API in the project