• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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;
      }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#和JAVA的RSA密钥、公钥转换发布时间:2022-07-13
下一篇:
转Visualc#对话框(一)发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap