asp.net webapi 參數綁定總結

來源:互聯網
上載者:User

標籤:

 首先必須得更正下自己一直以來對於get請求和post請求理解的一個誤區:get請求只能通過url傳參,post請求只能通過body傳參。

其實上面的理解是錯誤的,翻閱了不少資料及具體實踐,正確理解應該是:get和post是http協議(規範)定義的和伺服器互動的不同方法,get用於從伺服器擷取資源(安全和等冪),post用於修改伺服器上的資源。傳參方式和請求方式沒有任何關係,get和post請求既可以接受url傳參,也可以接收body傳參,取決於服務端的參數綁定機制。

OK,回到主題,webapi參數綁定最佳實務,直接上例子:

1:簡單類型參數綁定&url傳參:

服務端:

[HttpGet]
[HttpPost]
public HttpResponseMessage FinnTest(string name,int age)
{
var json = "{name:‘" + name + "‘,age:" + age + "}";
var resp = new HttpResponseMessage
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
return resp;
}

用戶端調用調用:

post http://localhost:27984/HjkDealer/FinnTest?name=finn&age=88 http/1.1

2:簡單類型參數綁定&body傳參

服務端:

[HttpGet]
[HttpPost]
public HttpResponseMessage FinnTest2([FromBody]string name, int age)
{
var json = "{name:‘" + name + "‘,age:" + age + "}";
var resp = new HttpResponseMessage
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
return resp;
}

用戶端調用:

post http://localhost:27984/HjkDealer/FinnTest2?age=88 http/1.1
content-type:application/x-www-form-urlencoded;charset=utf-8

=finn

注意紅色標註:content-type頭部必須,否則name參數不能正確接收;body體如果寫成:“name=finn”或“finn”,name參數也不能正確接收,深層次原因尚不清楚

3:複雜類型參數綁定&body傳參(複雜類型預設body傳參)

public class fiona
{
public string name { get; set; }

public string age { get; set; }
}

[HttpGet]
[HttpPost]
public HttpResponseMessage FinnTest4(fiona fiona)
{
var json = "{name:‘" + fiona.name + "‘,age:" + fiona.age + "}";
var resp = new HttpResponseMessage
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
return resp;
}

 用戶端調用:

post http://localhost:27984/HjkDealer/FinnTest4 http/1.1
content-type:application/x-www-form-urlencoded;charset=utf-8

name=finn&age=88

4:List複雜類型參數綁定&body的json方式傳參(複雜類型預設body傳參)

服務端:

[HttpGet]
[HttpPost]
public HttpResponseMessage FinnTest5(List<fiona> fi)
{
var json = "{name:‘" + fi[0].name + "‘,age:" + fi[0].age + "}";
var resp = new HttpResponseMessage
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
return resp;
}

用戶端調用:

post http://localhost:27984/HjkDealer/FinnTest5 http/1.1
content-type:application/json

[{name:"finn",age:88},{name:"fiona",age:99}]

asp.net webapi 參數綁定總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.