首页 > 代码库 > C#调用接口接收结果【Get,Post通用】

C#调用接口接收结果【Get,Post通用】

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 = http://www.mamicode.com/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 = http://www.mamicode.com/new { title = false, message = "认证错误,拒绝访问" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                        }
                    }
                    else
                    {
                        filterContext.Result = new JsonResult { Data = http://www.mamicode.com/new { title = false, message = "认证错误,拒绝访问" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                    }
                }
                else
                {
                    filterContext.Result = new JsonResult { Data = http://www.mamicode.com/new { title = false, message = "认证错误,拒绝访问" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                }
            }
            else {
                filterContext.Result = new JsonResult { Data = http://www.mamicode.com/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通用】