zoukankan      html  css  js  c++  java
  • 关于RESTful 的使用(实战)

        今天在博客园首页看到一篇关于写 RESTful, 大致就是前端定义的一种规范. 原文如下, 

    https://www.cnblogs.com/zhangmumu/p/11936262.html

      看了一圈才发现,  在目前的公司,  4年来一直在用这种 "规范",  感觉也就是约定俗成的东西.

    首先说一下, API接口的 路由配置 WebApiConfig.cs 

     

      第一步: 代码如下,  这里路由格式为     v1/{controller}/{id}   , 版本 指定 v1

     public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "v1/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                config.EnableSystemDiagnosticsTracing();
            }
        }

     第二步: 对于API接口 返回的内容, 做一个规范 (这里一般返回json数据) , 结果实体类如下:

     //WebAPI 数据结果类
        public class Root<T>
        {
            public bool Result { get; set; }
            public string ErrorCode { get; set; }
            public string Message { get; set; }
    
            public T Data { get; set; }
    
            public Root()
            {
    
            }
    
            public Root(bool r, string e, string m)
            {
                Result = r;
                ErrorCode = e;
                Message = m;
            }
    
            public Root(bool r, string e, string m, T data)
            {
                Result = r;
                ErrorCode = e;
                Message = m;
                Data = data;
            }
    
        }

    第三步: API 接口定义

      public class GetXxDataController : ApiController
        {
            // 这里有一行权限验证 代码 (...)
            public HttpResponseMessage Post([FromBody]QueryParms parms)  //QueryParms 是一个 类,参数字段都在这个类里面
            {
                string msg;
                try
                {
                    string json = new XxDataBLL().QueryXxData(parms); //直接返回 json信息

                       //如果是返回某一个实体类(或者List<T>) , 将其 json 序列化一下. 

                       // string json = Newtonsoft.Json.JsonConvert.SerializeObject(List<T>);

    
                    Root<string> root = new Root<string>()
                    {
                        Result = true,
                        ErrorCode = "0",
                        Message = "",
                        Data = json
                    };
    
    
                  
    /*  
    //或者直接 返回 Root<T>
                    List<XxData> dataList = new XxDataBLL().QueryXxDataList(parms);//一个查询方法, 返回一个 List<T>
    
    
                    Root<XxData> root = new Root<XxData>()

                      {
                 Result = true,
                      ErrorCode = "0",
                     Message = "接口调用成功!",
                   Data = 
    dataList 

               };

                  */
                   return Request.CreateResponse(HttpStatusCode.OK, root);
    
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        msg = ex.InnerException.Message;
                    }
                    else
                    {
                        msg = ex.Message;
                    }
                    return Request.CreateResponse(HttpStatusCode.OK, new Root<string>(false, "-1", msg)); //如果出错返回一个错误的json, 状态是 false.
                }
    
            }
    
        }

    补充一下后续的使用:

     页面前端调用API 我就不说了, 反正一般 就是 jquery ajax 之类的.

    后端调用API统一方案

    1.准备好 调用 POST的 参数

       string newUrl=" http://xxxx.xxxx.xxxx.xxxx/XxDataAPI/v1/GetXxData";

    string postdata="account=?&pwd=?&id=?"; // 将?替换成对应的参数值

    2. 后台方法

      

       public string GetJsonDataByPostUrl(string newUrl, string postString)
            {
                byte[] postData = System.Text.Encoding.UTF8.GetBytes(postString); //编码,尤其是汉字,事先要看下抓取网页的编码方式  
                using (WebClient client = new WebClient())
                {
                    client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    //采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可  
                    client.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01");
    
                    byte[] responseData = client.UploadData(newUrl, "POST", postData); //得到返回字符流 
    
                    string jsonstr = Encoding.UTF8.GetString(responseData);
    
                    return jsonstr;
                }
            }

       然后调用:

    string json = GetJsonDataByPostUrl(newUrl, postdata); //先拿到接口返回的json, 可以写日志记录下来, 顺便把接口调用的参数也记录下来
    
    Root<XxData> xxdata = JsonConvert.DeserializeObject<XxData>(json);
    if (xxdata !=null&&xxdata.Result == true)
    {
       //使用逻辑....
    }

            如果  接口返回的是一个实体类对象(或者list<T>)  , 但是 原接口出错, 返回   new Root<string>(false, "-1", msg);

    Root<XxData> xxdata = JsonConvert.DeserializeObject<XxData>(json); 反序列化之后, 得到的对象 xxdata.Result 就是 false,

    回头查问题, 看看日志里面记录的json 日志信息就行了.
    
    
    
  • 相关阅读:
    codeforces 560 B. Gerald is into Art (模拟)
    导航控制器属性和基本使用
    多控制器和导航控制器简单介绍
    SQLite数据库框架--FMDB简单介绍
    数据库sqlite3的使用-ios中引用方法
    数据库sqlite3的使用-代码实例应用
    数据库sqlite3的使用-基本语法
    数据库sqlite3的使用-Navicat的安装
    如何制作.a静态库?合成多架构静态库?
    苹果Instruments/Shark性能调试工具概述
  • 原文地址:https://www.cnblogs.com/mjxxsc/p/11941962.html
Copyright © 2011-2022 走看看