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進行請求。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM