之前看了http://www.cnblogs.com/dudu/archive/2012/05/11/asp_net_webapi_httpclient.html寫的httpclient+webapi的一個例子,參考他的代碼子階寫了一個,結果請求服務獲取的參數都是空的,而將參數綁定在url中則可以正常得到參數,折騰好久,終於在網上找到了相關資料,原來RC版WebApi在參數綁定上發生了些變化。
rc版的webapi參數綁定器分為兩種:
1.Model Binding
2.Formatters
其中Model Binding僅從url中取值,這點是與mvc的model binding有區別的,
formatters是從request的body中取值,並且是把整個body作為一個(不可為多個)對象解析為一個參數。
/?id=123&name=bob void Action(int id, string name) // 兩個參數都是基本類型,則從url中獲取
/?id=123&name=bob void Action([FromUri] int id, [FromUri] string name) // 標記為FromUri的參數從url中獲取.
void Action([FromBody] string name); // 標記為FromBody的參數從request的body中取值.
public class Customer { // a complex object public string Name { get; set; } public int Age { get; set; } }
/?id=123 void Action(int id, Customer c) // id 從url獲取, c 是一個自定義類型,從request的body中取值.
void Action(Customer c1, Customer c2) // 這樣的寫法是錯誤的,從request的body中取值的參數只能有一個
void Action([FromUri] Customer c1, Customer c2) // 這樣是正確的, c1 從url獲取 、 c2 從request的body中取值
void Action([ModelBinder(MyCustomBinder)] SomeType c) //指定一個明確的模型綁定器使用來創建參數.
// 位置屬性類型聲明應用於所有的參數實例 [ModelBinder(MyCustomBinder)] public class SomeType { }
void Action(SomeType c) // c的類型指定使用model binding.
到此,已經明白為什么RC版下服務獲取參數為空了,也知道如何處理了。