接口传参几种方式

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值