WebApi參數傳遞總結

來源:互聯網
上載者:User

標籤:style   http   使用   os   io   for   ar   cti   

在WebAPI中,請求主體(HttpContent)只能被讀取一次,不被緩衝,只能向前讀取的流。

舉例子說明:

1. 請求地址:/?id=123&name=bob 

    服務端方法: void Action(int id, string name) // 所有參數都是簡單類型,因而都將來自url

2. 請求地址:/?id=123&name=bob 

    服務端方法: void Action([FromUri] int id, [FromUri] string name) // 同上

                      void Action([FromBody] string name); //[FormBody]特性顯示標明讀取整個body為一個字串作為參數

3. 請求地址: /?id=123 

    類定義:

public class Customer {   // 定義的一個複雜物件類型 
  public string Name { get; set; } 
  public int Age { get; set; } 
}

    服務端方法: void Action(int id, Customer c) // 參數id從query string中讀取,參數c是一個複雜Customer對象類戲,通過formatter從body中讀取

    服務端方法: void Action(Customer c1, Customer c2) // 出錯!多個參數都是複雜類型,都試圖從body中讀取,而body只能被讀取一次

    服務端方法: void Action([FromUri] Customer c1, Customer c2) // 可以!不同於上面的action,複雜類型c1將從url中讀取,c2將從body中讀取

4.ModelBinder方式:

void Action([ModelBinder(MyCustomBinder)] SomeType c) // 標示使用特定的model binder來解析參數

[ModelBinder(MyCustomBinder)] public class SomeType { } // 通過給特定類型SomeType聲明標註[ModelBidner(MyCustomBinder)]特性使得所有SomeType型別參數應用此規則 

void Action(SomeType c) // 由於c的類型為SomeType,因而應用SomeType上的特性決定其採用model binding

 

總結:

1. 預設簡單參數都通過URL參數方式傳遞,例外:

1.1 如果路由中包含了Id參數,則id參數通過路由方式傳遞;

1.2 如果參數被標記為[FromBody],則可以該參數可以為簡單參數,用戶端通過POST方式傳遞:$.ajax(url, ‘=value‘),或者$.ajax({url: url, data: {‘‘: ‘value‘}});

2. 預設複雜參數(自訂實體類)都通過POST方式傳遞,例外:

2.1 如果參數值被標記為[FromUri], 則該參數可以為複雜參數;

3. 被標記為[FromBody]的參數只允許出現一次, 被標記為[FromUri]的參數可以出現多次,如果被標記為[FromUri]的參數是簡單參數,該標記可以去掉。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.