1.创建API项目,创建步骤省略
2.在WebConfig 进行配置,添加Appkey的值(由自己定义),其目的是为了后面对接口进行拼接加密
3.如果请求数据库的值,需要加上数据库配置
4.以上均完成后,就来书写我们的接口
1)创建控制器 注意:创建的webApi控制器
2)创建类
3)添加md5加密方法(可在网上自行百度,此方法仅供参考)
public static string md5(string password)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
var hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(password));
StringBuilder tmp = new StringBuilder();
foreach (byte i in hashedDataBytes)
{
tmp.Append(i.ToString("X2"));
}
return tmp.ToString();
}
4)添加验证方法 ,用来判断传来的签名值是否合法
public static bool IsEmpower(Models.pramers pramers)
{
string AppKey = ConfigurationManager.AppSettings["AppKey"];
#region 判断请求是否过期200秒
//DateTime requestTime = TimeHelper.GetTime(Convert.ToInt64(timestamp), true);
//if (requestTime.AddSeconds(200) < DateTime.Now)
//{
// return false;
//}
#endregion
#region 校验签名是否合法
string param = "appKey" + AppKey + "_timestamp" + pramers.timestamp;
string currentSign = md5(param);
if (pramers.Sign != currentSign)
{
return false;
}
else
{
return true;
}
#endregion
}
5)书写接口,获取数据
[HttpPost]
public string GetTest(Models.pramers pramers)
{
try
{
if (!IsEmpower(pramers))
return Newtonsoft.Json.JsonConvert.SerializeObject(new { code = 0, msg = "没有授权" });
}
catch (Exception)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new { code = 0, msg = "没有授权" });
}
return JsonConvert.SerializeObject(branch.GetTableList());
}
写到这里,我们的 接口层就写完了,接口层实现的就是对传过来的数据进行一个验证并且获取数据的功能
接下来就写调用层
1.创建一个mvc项目(注:可自行创建,也可创建winform项目以及其他项目)
需要创建实体类,以及帮助类
1)HttpHelper帮助类:
public static string HttpGet(string url, Dictionary<string, string> headers = null, int timeout = 0)
{
string msg = url;
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = new TimeSpan(0, 0, timeout);
}
try
{
Byte[] resultBytes = client.GetByteArrayAsync(msg).Result;
return Encoding.UTF8.GetString(resultBytes);
}
catch (Exception ex)
{
return "";
throw;
}
}
}
/// <summary>
/// Http Get 同步方法
/// </summary>
/// <param name="url"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string NewHttpGet(string url, Encoding encoding = null)
{
HttpClient httpClient = new HttpClient();
var t = httpClient.GetByteArrayAsync(url);
t.Wait();
var ret = encoding.GetString(t.Result);
return ret;
}
/// <summary>
/// 同步GET请求(返回JSon对象)
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
/// <returns></returns>
public static JObject HttpGetJObject(string url)
{
return StringToJson(HttpGet(url));
}
#region string字符串转Json对象
/// <summary>
/// string字符串转Json对象
/// </summary>
/// <param name="buff"></param>
/// <returns></returns>
public static JObject StringToJson(string buff)
{
return (JObject)JsonConvert.DeserializeObject(buff);
}
#endregion
/// <summary>
/// 异步GET请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
/// <returns></returns>
public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null, int timeout = 0)
{
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = new TimeSpan(0, 0, timeout);
}
Byte[] resultBytes = await client.GetByteArrayAsync(url);
return Encoding.Default.GetString(resultBytes);
}
}
/// <summary>
/// 同步POST请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
/// <param name="encoding">默认UTF8</param>
/// <param name="encoding">默认UTF8</param>
/// <returns></returns>
public static string HttpPost(string url, string postData, Dictionary<string, string> headers = null, string contentType = "application/json", int timeout = 0, Encoding encoding = null)
{
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = new TimeSpan(0, 0, timeout);
}
using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
{
if (contentType != null)
{
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
}
using (HttpResponseMessage responseMessage = client.PostAsync(url, content).Result)
{
Byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
return Encoding.UTF8.GetString(resultBytes);
}
}
}
}
/// <summary>
/// 同步Delete请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
/// <param name="encoding">默认UTF8</param>
/// <returns></returns>
public static string HttpDelete(string url, string postData, Dictionary<string, string> headers = null, string contentType = null, int timeout = 0, Encoding encoding = null)
{
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = new TimeSpan(0, 0, timeout);
}
using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
{
if (contentType != null)
{
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
}
using (HttpResponseMessage responseMessage = client.DeleteAsync(url).Result)
{
Byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
return Encoding.UTF8.GetString(resultBytes);
}
}
}
}
/// <summary>
/// 异步POST请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
/// <param name="encoding">默认UTF8</param>
/// <returns></returns>
public static async Task<string> HttpPostAsync(string url, string postData, Dictionary<string, string> headers = null, string contentType = null, int timeout = 0, Encoding encoding = null)
{
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = new TimeSpan(0, 0, timeout);
}
using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
{
if (contentType != null)
{
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
}
using (HttpResponseMessage responseMessage = await client.PostAsync(url, content))
{
Byte[] resultBytes = await responseMessage.Content.ReadAsByteArrayAsync();
return Encoding.UTF8.GetString(resultBytes);
}
}
}
}
2)md5加密类:
public static string md5(string password)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
var hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(password));
StringBuilder tmp = new StringBuilder();
foreach (byte i in hashedDataBytes)
{
tmp.Append(i.ToString("X2"));
}
return tmp.ToString();
}
2.一样需要配置webconfig,需注意的是Api层的appkey和调用层的appkey一样
3.然后就开始写控制器层:
public ActionResult Index()
{
Models.pramers pramers = new Models.pramers();
string AppKey = ConfigurationManager.AppSettings["AppKey"];
pramers.timestamp = GetTimeStamp(DateTime.Now).ToString();
string param = "appKey" + AppKey + "_timestamp" + pramers.timestamp;
string currentSign = MD5Helper.md5(param);
pramers.Sign = currentSign;
var jsonData = JsonConvert.SerializeObject(pramers);
//此处的路径获取APi的接口地址
HttpHelper.HttpPost("https://localhost:44365/api/Test/GetTest", jsonData);
return View();
}
//获取当前时间戳
//获取当前时间戳的方法可自行百度,方法很多
public string GetTimeStamp(DateTime dateTime)
{
TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
这样我们的加密就完成了
这个加密的原理就是用用户传来的签名值和APi生成的签名值是否一致来判断此次请求是否合法,如果不合法,则无法请求接口,其中用到了Md5加密,获取当前时间戳的方法可自行百度,方法很多
这是最简单的api加密方式此文章仅个人理解,不对欢迎指正