webapi創建及postman測試


調用接口一般采用兩種方式,webservice和webapi,此篇寫webapi建立及測試

1.創建:

       

 

 2.添加控制器到Controller文件夾,新建Api文件夾,將該控制器文件放入Api下,打開App_Start文件夾下webapiconfig,修改路由

 public static void Register(HttpConfiguration config)
        {
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

3.方法名定義注意點

a.如果方法名為post或者get,就是默認使用,在測試時,直接寫到控制器LQInfo,然后傳遞方式設置為post即可,不需要寫方法;

 

 

b.如果自定義方法,選擇方式為get或者post,那么需要寫到具體方法getcode();

 

在用 winform調用測試時,也需要寫到方法:

 private void button1_Click(object sender, EventArgs e)
        {

            string ashxSite = "http://localhost:80//ActionApi";
            var client = new RestClient(ashxSite);
            var request = new RestRequest("/UserInfo/GetCode", Method.GET);
            request.AddParameter("Barcode", "WLS000021");
            var response = client.Execute(request); // 從 WebAPI 獲取 
            textBox2.Text = response.Content;

        }

4.參數注意點

a.如果參數只為一個:

      [HttpPost]
        public string GetCode(string Barcode) {

            try
            {
                using (OracleConnection conn = new OracleConnection(connERP))
                {
                
                    string sql = @"select  trim(a.t$mitm ) 編碼,trim(b.t$dsca) 名稱 from tablea  a  join tableb b
                   on trim(a.t$pdno)=:a and a.t$mitm = b.t$item";

                    Object obj = conn.QueryFirstOrDefault(sql, new { a = Barcode });

                    if (obj != null)
                    {

                        string item = obj.ToString();

                        return item;
                    } 

                    else return null;
                }



            }
            catch (Exception ex) { return "Error." + ex.Message; }
           
        }

b.從URL獲取參數值的方式的弊端是URL有長度限制,當超過瀏覽器的最大URL長度時請求將被瀏覽器拒絕,根本不會發出去。

因此,當參數值過大時需要用[FromBody]參數進行傳輸,相當於一個類,將參數包含起來,使用postman測試時,參數列舉見圖3-a.

 

    public class AX
        {
            public string url { get; set; }
        }

        public  string Post([FromBody] AX arg )
     
        {

            
            //  傳入的字符串:"action=search&arg1=" + user + "&arg2=" + ED_tiaoMa.getText().toString();
            //  先用&分割,再用=分割
            string ip = HttpContext.Current.Request.UserHostAddress;
            if (arg!= null && !string.IsNullOrEmpty(arg.url)) {

                log.DebugFormat("Post:{0}", arg.url);
                var tmps = arg.url.Split('&');
                string action = string.Empty;
                string arg1 = string.Empty;
                string arg2 = string.Empty;
                string arg3 = string.Empty;
                string arg4 = string.Empty;

                foreach (var item in tmps) {

                    var tmps2 = item.Split('=');
                    var s = tmps2[0].Trim().ToLower();   //第一個參數    方法
                    var _value = tmps2[tmps2.Length - 1].Trim();  //最后一個參數    
                    if (tmps2.Length < 2) 
                        _value = string.Empty;
                    if ("action".Equals(s, StringComparison.OrdinalIgnoreCase))
                        action = _value;
                    else if ("arg1".Equals(s, StringComparison.OrdinalIgnoreCase))
                        arg1 = _value;
                    else if ("arg2".Equals(s, StringComparison.OrdinalIgnoreCase))
                        arg2 = _value;
                    else if ("arg3".Equals(s, StringComparison.OrdinalIgnoreCase))
                        arg3 = _value;
                    else if ("arg4".Equals(s, StringComparison.OrdinalIgnoreCase))
                        arg4 = _value;
                    
                }

                log.DebugFormat("Post: {0} / {1} / {2} / {3} / {4} / {5}", action, arg1, arg2, arg3, arg4,  ip);
                if (string.IsNullOrWhiteSpace(action))
                    return "不支持此方法!";

                var a1 = action.Trim().ToLower();
                switch (a1)
                {
                    case "getcode":
                        {
                            try
                            {
                                using (OracleConnection conn = new OracleConnection(connErp))
                                {

                                    string sql = @"select  trim(a.t$mitm ) 編碼,trim(b.t$dsca) 名稱 from  tablea  a  join tableb b
                   on trim(a.t$pdno)=:a and a.t$mitm = b.t$item";

                                    Object obj = conn.QueryFirstOrDefault(sql, new { a = arg1 });

                                    if (obj != null)
                                    {

                                        string item = obj.ToString();

                                        return item;
                                    }

                                    else return null;
                                }

                            }
                            catch (Exception ex) { return "Error." + ex.Message; }                         
                        }

                        return action;

                
                }

            }


            return "Error." + arg.url;
       

        }

VS附加到進程調試(不用發布,可被調用)

點擊調試-屬性

 

 

 選擇調試—附加到進程,顯示所有用戶進程,找到w3wp進程,附加

 

進行生成,在postman調試

如果出現不進斷點情況,右下角帶感嘆號,但是訪問數據成功。檢查重裝電腦.net版本,對應應用程序。再試即可

【注】調用webapi時,便於他人解析,一般用JsonResult作為返回類型,

new JsonResult(){Data=""};

new JsonResult(){Data=lista};

 


免責聲明!

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



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