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

來源:互聯網
上載者:User

標籤:head   提交   charset   split   nat   start   manage   ase   pwd   

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通用】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.