1. 程式人生 > >C#調用接口接收結果【Get,Post通用】

C#調用接口接收結果【Get,Post通用】

class 1.2 style lac pass ide 參數 判斷 ext

1.首先,客戶端調用接口的實例

1.1 先定義接收接口結果類

public class ResultMsg
    {
        public bool title { get; set; }
        public string message { get; set; }
        public string other { get; set; }
    }

1.2 以用戶登陸為例,登陸時請求接口輸入參數用戶名密碼判斷是否正確

public static ResultMsg CheckLogin(string account,string pwd)
        {
           
// Tools.Common1.WriteLog("checklogin", "checklogin", "account:" + account + "----pwd:" + pwd); WebApiResult msg = WebApiHelper.GetWebApi(new { UserName = account, PassWord = pwd }, "/UserAccounts/Login/"); if (msg.Success) { return msg.result; }
else { return new ResultMsg() { title = false, message = "請求接口失敗,"+msg.result.message }; } }

調用接口處,在header裏添加訪問的賬號密碼來提升接口的安全度

private const string pwd = "abc_2015?";
       private const string account = "webaccount";
       #region 請求webapi
       
       ///
<summary> /// 請求webapi /// </summary> /// <param name="model"></param> /// <param name="page"></param> /// <returns></returns> public static WebApiResult GetWebApi(object model, string path) { WebClient wc = new WebClient(); wc.Headers.Add(HttpRequestHeader.Accept, "application/json"); wc.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8"); string auth = AuthorizationHelper.GetAuthorization1(account, path, pwd); wc.Headers.Add(HttpRequestHeader.Authorization,auth); byte[] postData = System.Text.Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(model)); try { byte[] text = wc.UploadData(domain + path, "post", postData); string str = System.Text.Encoding.UTF8.GetString(text); return new JavaScriptSerializer().Deserialize<WebApiResult>(str); } catch(Exception ex){ return new WebApiResult() { Success = false, result = new ResultMsg() { title = false, message = ex.Message } }; } } #endregion }

1.3接口在另一個項目中,實例如下:

在接口項目的app_start文件夾下,新建類LoginAttribute來判別header裏傳輸的賬號密碼是否正確

    //標示該特性能用於類、方法,特性不能被重復放置在同一個程序實體前多次
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class LoginAttribute : ActionFilterAttribute
    {
       /// <summary>
        /// 在action執行前
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //過濾器上下文為空,拋出異常
            if (filterContext == null)
            {
                throw new ArgumentException("filterContext");
            }
            //獲取訪問路徑、賬號、時間戳、密文
            var path = filterContext.HttpContext.Request.Path.ToString();
            var authorization = filterContext.HttpContext.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(authorization))
            {
                //分割驗證字符串, account,mac,salt
                string[] strs = authorization.Split(,);
                if (strs.Length == 3)
                {
                    string account = strs[0].Replace("account=", "");
                    var mac = strs[1].Replace("mac=", "");
                    var salt = strs[2].Replace("salt=", "");
                    if (!string.IsNullOrEmpty(account))
                    {
                        try
                        {
                            var pwd = System.Configuration.ConfigurationManager.AppSettings[account].ToString();
                            string ciphertext = Uri.EscapeDataString(PISCenter.Common.Utility.GetCiphertext(account, path, salt, pwd));
                            if (ciphertext.Equals(mac))
                            {
                                base.OnActionExecuting(filterContext);
                            }
                        }
                        catch
                        {
                            filterContext.Result = new JsonResult { Data = new { title = false, message = "認證錯誤,拒絕訪問" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                        }
                    }
                    else
                    {
                        filterContext.Result = new JsonResult { Data = new { title = false, message = "認證錯誤,拒絕訪問" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                    }
                }
                else
                {
                    filterContext.Result = new JsonResult { Data = new { title = false, message = "認證錯誤,拒絕訪問" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                }
            }
            else {
                filterContext.Result = new JsonResult { Data = new { title = false, message = "認證錯誤,拒絕訪問" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };                
            }
            
        }
    }

1.4 登陸的方法體

        [HttpPost]
        public JsonResult Login(CheckLoginInput model)
        {
            if (model == null||string.IsNullOrEmpty(model.PassWord)||(string.IsNullOrEmpty(model.UserName)&&string.IsNullOrEmpty(model.MobilePhone)))
            {
                return Fail("提交參數不正確");
            }
            CheckLoginOutPut ua=_useraccountsAppService.CheckLogin(model);
            if (ua!=null&&ua.Id>0)
            {
                return Success(Newtonsoft.Json.JsonConvert.SerializeObject(ua));
            }
            else {
                return Fail("登錄失敗,賬號或密碼錯誤");
            }
        }

整個流程結束

附:項目裏

public static string GetAuthorization1(string account, string path,string password)
      {
          StringBuilder sb = new StringBuilder();
          string date=Uri.EscapeDataString(GetTimeStamp());
          sb.AppendFormat("account={0},mac={1},salt={2}", Uri.EscapeDataString(account), Uri.EscapeDataString(GetCiphertext(account, path, date,password)), date);
          return sb.ToString();
      }

接口項目裏:

/// <summary>
      /// 對訪問者進行SHA-1加密,返回加密的密文
      /// </summary>
      /// <param name="account">賬號</param>
      /// <param name="path">訪問路徑 /開頭,/結尾</param>
      /// <param name="date">時間戳</param>
      /// <param name="password">密碼</param>
      /// <returns></returns>
      public static string GetCiphertext(string account, string path, string date, string password)
      {
          string ciphertext = account + "\n" + date + "\n" + path.ToLower() + "\n" + password + "\n";
          System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1();
          hmacsha1.Key = Encoding.UTF8.GetBytes(password);
          byte[] dataBuffer = Encoding.UTF8.GetBytes(ciphertext);
          byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
          ciphertext = Convert.ToBase64String(hashBytes);
          return ciphertext;
      }

C#調用接口接收結果【Get,Post通用】