asp.net中http接口的开发

第一篇博客,如有不足请大家多多谅解。

最近一段时间主导着一个app的开发。所有功能都交给后台接口进行处理。采用http,传输的数据类型为json。

http接口是一种基于基于TCP、http服务的api,有3次握手,文本传输协议,项目与项目之间互相请求的一种规范约定,其实归根结底,webservice、webapi都是一种http接口。只不过更加规范一点。

http接口好处呢?协议群众基础广,开发调试方便,可以跨语言、跨系统的进行调用。比如我asp.net开发的接口,java可以调用、ios可以调用、php也可以进行调用,无论pc或移动端。接下来就用一个简单的例子说明吧。

 

1.用程序包管理器导入Newtonsoft.Json包(C#Json序列化工具) 命令行:pm> install-package newtonsoft.json

2.建父类,每个aspx继承父类,可添加sign进行权限验证,op为接口名称,entity为解析后的json数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace XKFWEB
{
    /// <summary>
    /// 通用权限验证父类
    /// </summary>
    public class PageBase : System.Web.UI.Page
    {
        //验证状态
        protected bool Sign
        {
            get
            {
                try
                {
                    //BC.Common.Encrypt.DESDecrypt_China(Request["sign"] ?? BC.Common.Utilty.GenderGuid());
                    string testKey = BC.Common.Encrypt.DESEncrypt_China(BC.Common.Utilty.GetWebConfig("testKey"));//方便本地测试
                    BC.Common.Encrypt.DESDecrypt_China(testKey ?? BC.Common.Utilty.GenderGuid());
                    return true;
                }
                catch
                {

                }

                return false;
            }
        }

        //操作类型参数
        protected string OP
        {
            get
            {
                return Request["op"] ?? "";
            }
        }

        protected dynamic entity = "";

        protected override void OnInit(EventArgs e)
        {

            string jsonData = Server.UrlDecode(Request["jsonData"] ?? "");
            entity = JsonConvert.DeserializeObject<dynamic>(jsonData);

            if (OP!="register" )
            {
                if (!Sign)
                {
                    Response.Write("非法操作");
                    Response.End();
                }
            }
            
        }
    }

}

3.新建一个aspx,继承PageBase父类。写一个通用登录的接口,所需参数(手机号(账号):uName,密码:uPwd,微信Id,设备码:xIMEI)

判断接口op参数,并跳转到对应方法

 private void userLogin()
        {
            try
            {
                Dictionary<string, dynamic> dict = new Dictionary<string, dynamic>();
                List<dynamic> list = new List<dynamic>();
                string md5Pwd = BC.Common.Encrypt.MD5(entity["uPwd"].ToString());
                string wxId = entity["wxId"].ToString();
                string xIMEI = entity.xIMEI;//设备码 
                DataTable dt = business.login(entity["uName"].ToString(), md5Pwd, wxId);//账号:uName,密码:uPwd,设备码if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        list.Add(new { UserId = row["UserId"], UserLogin = row["UserLogin"], UserMobile = row["UserMobile"], RealName = row["RealName"], UserFace = row["UserFace"], Signature = row["Signature"], Description = row["Description"], AddDate = BC.Common.Utilty.DateTimeToString(Convert.ToDateTime(row["AddDate"])), EditDate = BC.Common.Utilty.DateTimeToString(Convert.ToDateTime(row["EditDate"])), EnableCourse = row["EnableCourse"], EnableInfo = row["EnableInfo"] });
                        userId = row["UserId"].ToString();

                        business.addLog("userLogin", "" + RealName + " 登录小课坊", "", xIMEI, "用户登录", UserId);
                    }
                    Response.Write(BC.Common.Utilty.Serialize(new { Return = "0", sign = BC.Common.Encrypt.DESEncrypt_China(UserId), list = list }));
                }
                else
                {
                    Response.Write(utilty.LoadErrorMessage("登录失败,账户或密码错误"));
                }
            }

            catch (Exception E)
            {
                Response.Write(utilty.LoadErrorMessage(E.Message));
            }
        }

 

请求路径以及数据:(域名)+/user/userInfo.aspx?op=login&jsonData={"uName":"13786868686","uPwd":"970512","xIMEI":"123","wxId":""}   (注意,jsonData需严格按照json格式,并且要Url Encode)

接口中获取请求的json方法有两种: entity["参数名称"]      entity.参数名称  entity为PageBase父类解析好的JsonData

返回给用户请求的数据可在Response.Write中自定义,最好带上请求响应状态,需Serialize

 

请求成功响应json数据:

{
    "Return": "0",
    "sign": "CBC41724059BD521B640CDA5BC99DFB815FD5E532F6D09FD",
    "list": [{
        "UserId": "dsadeqe2397-1239dsa-1",
        "UserLogin": "13928282828",
        "UserMobile": "13928282828",
        "RealName": "王继峰",
        "UserFace": "/img/userImg/wjf.jpg",
        "Signature": "公司放假还早着呢,努力工作吧。",
        "Description": "我的名字叫做王继峰,性别男,职业程序员这是我很长的一段个人自我简介数据字段 Description",
        "AddDate": "2018-01-19 17:56:43",
        "EditDate": "2018-01-19 17:56:43",
        "EnableCourse": 1,
        "EnableInfo": 1
    }]
}

 

总结:接口是一种约定,请求与输出的参数都必须遵循这个约定。http采用post进行请求。

posted @ 2018-03-09 17:35  王继峰  阅读(15303)  评论(1编辑  收藏  举报