Bootstrap

接口传参几种方式

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

转载于:https://www.cnblogs.com/jiao006/p/8057226.html

;