C#開發微信小程序(三)


 

關於小程序項目結構,框架介紹,組件說明等,請查看微信小程序官方文檔,關於以下貼出來的代碼部分我只是截取了一些片段,方便說明問題,如果需要查看完整源代碼,可以在我的項目庫中下載:

https://e.coding.net/dwBurning/ReallyWantToApi.git
https://e.coding.net/dwBurning/LazyOrders.git

第二篇博文介紹的對微信小程序前端調整的過程中發現的一些問題,該篇繼續介紹對后端Web Api調整的過程中發現的問題,雖然談不上是bug,但是規范性同樣很重要,當然如果仍有不足之處,歡迎在評論中指出來。

 第一:調整接口,最初的版本,為了方便都寫在一個類文件里邊,其次,不符合Api RESTful的風格,於是重新整理,針對每個資源,建一個類,里邊只有針對資源的增刪查改Get,Post,Put,Delete四個方法:

public JsonResult<ResultData> Get(string sessionKey){}

public JsonResult<ResultData> Post([FromBody]dynamic data){}

public void Put(int id, [FromBody]string value)

public JsonResult<ResultData> Delete([FromBody]dynamic data)

第二:登錄,小程序開放給所有的微信用戶的,所以每個人打開都需要獲取到用戶的唯一標識,叫做OpenId,這個是微信服務端分配給每個微信用戶的唯一憑證,我們要拿這個憑證建立用戶關系,下單,查詢購物車之類的操作。通過官方文件的介紹,可以知道,調用如下這個接口,就可以獲取到。但是同時官方是不建議將獲取到的敏感數據直接返回小程序前端的,於是稍微調整了一下,在緩存中重新建立了映射關系,返回自己生成的sessionKey給前端。批注:目前整個應用都是基於緩存的,並沒有實現真正的倉儲。

另外補充說明一下,這里使用dynamic作為參數的數據類型,因為小程序前端發起的請求,提交參數都是JSON字符串,每次都解析的話,也挺麻煩的,用dynamic省去了這個步驟。

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
private readonly string _appID = "";//填寫自己的AppId

private readonly string _appSecret = "";//填寫自己的AppSecret

/// <summary>
/// 登錄
/// </summary>
/// <param name="data">dynamic接收{code:""}</param>
/// <returns>sessionKey</returns>
public string PostLogIn([FromBody]dynamic data)
{
    string code = data.code;
    string strUrl = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", _appID, _appSecret, code);

    var appAuth = JsonConvert.DeserializeAnonymousType(HttpRequestHelper.HttpGet(strUrl), new
    {
        session_key = "",
        openid = ""
    });

    string sessionKey = Guid.NewGuid().ToString("N");
    string sessionValue = appAuth.session_key + "|" + appAuth.openid;

    LazyOrdersRepository.AppSession.AddOrUpdate(sessionKey, sessionValue, (key, value) => value);

    return sessionKey;
}

第三,增加了統一的返回類型,直接返回JSON對象而不是JSON字符串。如果你看了我的第一篇文章,里邊就講到了如果直接返回String,前端需要將字符串轉JSON對象,才可以解析。此次修改為直接返回JsonResult對象,前端收到后,就可以不用再次轉換了。

/// <summary>
/// 根據sessionKey獲取購物車列表
/// </summary>
/// <param name="sessionKey">會話Key</param>
/// <returns>ResultData通用結果返回類型</returns>
public JsonResult<ResultData> Get(string sessionKey)
{
    string sessionValue = "";
    if (LazyOrdersRepository.AppSession.TryGetValue(sessionKey, out sessionValue))
    {
        string openId = sessionValue.Split('|')[1];
        var carts = from cart in LazyOrdersRepository.Carts
                    where cart.OpenId == openId && cart.IsPaid == false
                    group cart by cart.MenuId into c
                    select new
                    {
                        c.Key,
                        menu = LazyOrdersRepository.GetMenuList().FirstOrDefault(x => x.MenuId == c.Key),
                        count = c.Count(),
                        selected = true
                    };
        return Json<ResultData>(new ResultData() { Code = ResponseResult.Success, Context = carts.ToList() });
    }
    return Json(new ResultData() { Code = ResponseResult.Falied });
}
onShow() {
    const self = this;
    wx.getStorage({
      key: 'sessionKey',
      success: function(res) {
        self.setData({
          sessionKey: res.data
        })
        wx.request({
          url: app.globalData.urlCarts + '?sessionKey=' + self.data.sessionKey,
          success: function(res) {
            if (res.data.Context && res.data.Context.length > 0) {
              self.setData({
                hasList: true, // 既然有數據了,那設為true吧
                carts: res.data.Context
              });
            }
          },
          complete: function(res) {
            self.getTotalPrice()
          }
        });
      },
      fail: function(res) {
        util.checkSession()
      },
    })
  },

 第四:增加了swagger生成Api文檔,具體怎么配置swagger,可以移步之前寫的博文Asp.Net Web Api中使用Swagger

 


免責聲明!

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



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