(1) 訪問Rest ful介面時 Token驗證 返回數據格式封裝 (一)訪問時Token驗證 返回數據格式封裝 1.1訪問Api介面 方法 實現 1.1.1 創建訪問Restful Api幫助類 public static string MyGet = "GET"; public static ...
(1) 訪問Rest ful介面時 Token驗證 返回數據格式封裝
(一)訪問時Token驗證 返回數據格式封裝
1.1訪問Api介面 方法 實現
1.1.1 創建訪問Restful Api幫助類
public static string MyGet = "GET"; public static string MyPost = "POST"; public static string MyPut = "PUT"; public static string MyDELETE = "DELETE"; /// <summary> /// 訪問介面信息 /// </summary> /// <param name="JsonString">拋送的字元串</param> /// <param name="achieveUrl">訪問的路徑</param> /// <param name="PublishKey">密鑰Token</param> /// <param name="Method">訪問方法</param> /// <returns></returns> public static string SendService(string JsonString, string achieveUrl, string PublishKey, string Method) { //用於返回信息的記錄 var responseValue = string.Empty; if (!string.IsNullOrEmpty(achieveUrl)) { //基於http協議的請求響應 HttpWebRequest request = WebRequest.Create(achieveUrl) as HttpWebRequest; //提交方法 request.Method = Method; //設置Http標頭信息 request.UserAgent = ""; //設置請求超時時間 request.Timeout = 1000 * 60 * 30; //設置讀取/寫入超時時間 request.ReadWriteTimeout = 1000 * 60 * 30; //request.Headers.Add("", ""); request.Headers.Add("Token", PublishKey); request.ContentType = @"application/json"; //判斷訪問方法 if (Method != "GET" && Method != "PUT") { request.ContentLength = Encoding.UTF8.GetByteCount(JsonString); if (!string.IsNullOrEmpty(JsonString))//如果傳送的數據不為空,並且方法是put { var encoding = new UTF8Encoding(); var bytes = Encoding.GetEncoding("UTF-8").GetBytes(JsonString);// request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } } //http請求的返回狀態 using (var response = (HttpWebResponse)request.GetResponse()) { //獲取來自 伺服器或介面的響應信息 using (var responseStream = response.GetResponseStream()) { if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { responseValue = reader.ReadToEnd(); } } } } } return responseValue; }View Code
1.1.2 Token 加密方法
/// <summary> /// Base64加密 /// </summary> /// <param name="codeName">加密採用的編碼方式</param> /// <param name="source">待加密的明文</param> /// <returns></returns> public static string EncodeBase64(Encoding encode, string source) { string Result = ""; byte[] bytes = encode.GetBytes(source); try { Result = Convert.ToBase64String(bytes); } catch { Result = source; } return Result; } /// <summary> /// Base64加密,採用utf8編碼方式加密 /// </summary> /// <param name="source">待加密的明文</param> /// <returns>加密後的字元串</returns> public static string EncodeBase64(string source) { return EncodeBase64(Encoding.UTF8, source); }View Code
1.1.3 獲取本地IP 進行加密 用作Token
public string GetAddressIP() { ///獲取本地的IP地址 string AddressIP = string.Empty; foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (_IPAddress.AddressFamily.ToString() == "InterNetwork") { AddressIP = _IPAddress.ToString(); } } return AddressIP; }View Code
1.1.4 讀取Json文件 用作 訪問介面拋送的內容
public static string GetFileJson(string filepath) { string json = string.Empty; using (FileStream fs = new FileStream(filepath, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite)) { using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"))) { json = sr.ReadToEnd().ToString(); } } return json; }View Code
1.1.5 Json文件內容
{ "Name": "Szl", "Age": "30", "Address": "河南", "XXXXXX": "測試數據" }View Code
1.1.6 調用介面
// GET: Home public ActionResult Index() { string serviceURL = @"http://10.118.4.1x8:8082/szl/SzlAPI/Post"; string JsonString = GetFileJson(@"D:\VS2015Demo\RestServiceTest\UI\json.json"); string PublishKey = GetAddressIP(); ViewBag.Data = SendService(JsonString, serviceURL, EncodeBase64(PublishKey), "POST"); return View(); }View Code
1.2 Rest Api 介面聲明
1.2.1介面方法
/// <summary> /// AspNet Core Post請求 /// </summary> /// <param name="value">User類</param> /// <remarks> ///訪問參數 /// POST /// { /// "value": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb", /// } /// /// </remarks> /// <response code="201">返回新創建項</response> /// <response code="400">如果為空時</response> [HttpPost] [ProducesResponseType(typeof(User), 201)] [ProducesResponseType(typeof(User), 400)] public User Post([FromBody] User value) { //第二種接收值得方法 //Stream stream = HttpContext.Request.Body; //byte[] buffer = new byte[HttpContext.Request.ContentLength.Value]; //stream.Read(buffer, 0, buffer.Length); //string content = Encoding.UTF8.GetString(buffer); ////然後Json轉換 User Users = new User() { UserAddress = "北京", UserAge = "身體健康無頸椎病", UserName = "Szl", XXXXXX = "註意大小寫" }; return Users; }View Code
1.2.2 User類
public class User { /// <remarks> /// 名稱 /// </remarks> public string UserName { get; set; } = "名稱"; /// <summary> /// 年齡 /// </summary> public string UserAge { get; set; } /// <summary> /// 地址 /// </summary> public string UserAddress { get; set; } /// <summary> /// 測試欄位 /// </summary> public string XXXXXX { get; set; } }View Code
1.3 添加 幫助類 WebApiAuthorizationFilter 對介面訪問者身份Token 解密 獲取訪問者IP 進行驗證,對返回結果進行封裝
/// <summary> /// /// </summary> public class WebApiAuthorizationFilter : IAuthorizationFilter { /// <summary> /// 調用者的身份驗證 /// </summary> /// <param name="context"></param> public void OnAuthorization(AuthorizationFilterContext context) { //string IP = ((Microsoft.AspNetCore.Http.Internal.DefaultConnectionInfo)context.HttpContext.Connection).LocalIpAddress.ToString(); //獲取客戶端IP地址 string clientIP = ((Microsoft.AspNetCore.Http.Internal.DefaultConnectionInfo)context.HttpContext.Connection).RemoteIpAddress.ToString(); //獲取Token信息 var Token = context.HttpContext.Request.Headers["Token"].FirstOrDefault(); //驗證Token if (Token == "") { context.Result = new ObjectResult(new { Success = false, code = 404, msg = "請查看令牌是否包含!", data = "null" }); } else if (clientIP == DecodeBase64(Token)) { return; } else { context.Result = new ObjectResult(new { Success = false, code = 404, msg = "請查看令牌是否正確!", data = "null" }); } } /// <summary> /// Base64解密 /// </summary> /// <param name="codeName">解密採用的編碼方式,註意和加密時採用的方式一致</param> /// <param name="result">待解密的密文</param> /// <returns>解密後的字元串</returns> public static string DecodeBase64(Encoding codeName, string result) { string decode = ""; byte[] bytes = Convert.FromBase64String(result); try { decode = codeName.GetString(bytes); } catch { decode = result; } return decode; } /// <summary> /// Base64解密,採用utf8編碼方式解密 /// </summary> /// <param name="result">待解密的密文</param> /// <returns>解密後的字元串</returns> public static string DecodeBase64(string result) { return DecodeBase64(Encoding.UTF8, result); } }View Code
1.4 在Startup.cs中註冊服務啟用 WebApiAuthorizationFilter文件
services.AddMvc(options => { //身份驗證不通過是返回結果統一化 options.Filters.Add(typeof(WebApiAuthorizationFilter)); options.RespectBrowserAcceptHeader = true; });View Code
不加Token的結果
訪問正確結果
註意 返回結果中的data的欄位名 大小寫的變化 前邊的四位預設小寫了 這是框架本身Json序列化的結果
解決方法 在Startup.cs中註冊服務
services.AddMvc() //預設返回值 大小寫不變 .AddJsonOptions(op => op.SerializerSettings.ContractResolver =new Newtonsoft.Json.Serialization.DefaultContractResolver());View Code
今天結束 本來下麵的也要說說的太晚了留著明天吧
(2) 程式錯誤時 返回數據格式封裝
(3) 返回結果包裝
(4) 訪問方法時 參數必填與非必填的聲明
代碼中有不對的或者有更好的方法希望大家告之 相互學習 謝謝,轉載註明出處