接口傳參幾種方式


Post

  1. Querystring

最簡單,url中傳遞過來的參數,可以用request獲取,也可以在api的參數中獲取

Public  void   action(string a){}

 

  1. Form

用於接收表單數據,例如ajax中提交過來的數據

請求代碼

$.ajax({

            url: "http://localhost:5136/api/demo",

            dataType: "json",

            type: 'post',

            data: {a:1,b:2,value:"1231"},

            success: function (d) {

              

                        alert(d);

               

            }

        });

 

接收代碼 

HttpContext.Current.Request.From[“”]

 

  1. Content

將參數放在請求內容中

Public  void   action([FromBody]object id){}

 

請求代碼

  public void WebApiTest_AddProduct()

        {

            using (var client = new HttpClient())

            {

                client.BaseAddress = new Uri("http://localhost:5136/");

 

                var requestJson = JsonConvert.SerializeObject(

                    new

                    {

                        id = "1",

                        name = "2"

                    });

 

                HttpContent httpContent = new StringContent(requestJson);

                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

 

                var result = client.PostAsync("api/demo", httpContent).Result.Content.ReadAsStringAsync().Result;

                return;

            }

        }

 

 

 

  1. Body 文件流

將請求參數以文件流的形式提交

 

請求代碼

WebRequest req = WebRequest.Create("http://localhost:5136/api/demo");

            req.Method = "POST";

            req.ContentType = "application/json";

            byte[] data = Encoding.GetEncoding("UTF-8").GetBytes("{ \"a\":1,\"b\":2,\"value\":\"123\"}");

            req.ContentLength = data.Length;

            Stream sendStream = req.GetRequestStream();

            sendStream.Write(data, 0, data.Length);

            sendStream.Close();

            req.GetResponse();

 

 

 

#region 從文件流中獲取參數

            byte[] byts = new byte[HttpContext.Current.Request.InputStream.Length];

            HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length);

            string req = System.Text.Encoding.Default.GetString(byts);

 

            # endregion 從文件流中獲取參數

 

 

 

 

Put

方法接收參數,

參考http://www.cnblogs.com/shy1766IT/p/5237164.html

http://www.cnblogs.com/landeanfen/p/5337072.html

 

接收ajax參數,使用Request/Request.Form

其他同post

 

 

Get

通過路由匹配,或者request【】請求

Delete


免責聲明!

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



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