接口传参几种方式

时间:2024-10-22 07:14:53

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);

               

            }

        });

 

接收代码 

[“”]

 

  1. Content

将参数放在请求内容中

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

 

请求代码

  public void WebApiTest_AddProduct()

        {

            using (var client = new HttpClient())

            {

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

 

                var requestJson = (

                    new

                    {

                        id = "1",

                        name = "2"

                    });

 

                HttpContent httpContent = new StringContent(requestJson);

                 = new MediaTypeHeaderValue("application/json");

 

                var result = ("api/demo", httpContent).().Result;

                return;

            }

        }

 

 

 

  1. Body 文件流

将请求参数以文件流的形式提交

 

请求代码

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

            = "POST";

            = "application/json";

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

            = ;

            Stream sendStream = ();

            (data, 0, );

            ();

            ();

 

 

 

#region 从文件流中获取参数

            byte[] byts = new byte[];

            (byts, 0, );

            string req = (byts);

 

            # endregion 从文件流中获取参数

 

 

 

 

Put

方法接收参数,

参考/shy1766IT/p/

/landeanfen/p/

 

接收ajax参数,使用Request/

其他同post

 

 

Get

通过路由匹配,或者request【】请求

Delete