Web API 2.2 - Parameter binding attributes

Parameter Binding

想要知道傳過來的 request 的參數的來源是甚麼?
主要有 2 個
  • Primitive Type : int, string, boolean, …
  • Complex Type : 自己所定義的 object
在 Web API Controller 的 Action method 所傳進來的參數主要有 2 種, 一種是 primitive type, 另外一種是 Complex Type(Primitive Type 以外的 Type)
  • GET Primitive type
想要拿到某一個的 product

public class ProductController : ApiController
{
    public Product Get(int id) 
    {

    }
}

傳進來的參數有大小寫之分

如果傳進來的 parameter 是 Id, 那麼 endpoint 也要跟著改成 http://localhost:1234/api/product?Id=1

public class ProductController : ApiController
{
    public Product Get(int Id) 
    {

    }
}

順序可以互換

以下 2 個的Api endpoint 都是 http://localhost:1234/api/product?id=1&name=“”

public class ProductController : ApiController
{
    public Product Get(int id, string name) 
    {

    }
}

public class ProductController : ApiController
{
    public Product Get(string name, int id) 
    {

    }
}

但是這一個 API endpoint 就是 http://localhost:1234/api/product?id=1?&Name=“”
就會跟上面 2 個不一樣

public class ProductController : ApiController
{
    public Product Get(string Name, int id) 
    {

    }
}

FromBody

傳入一個 object 到 request body, 並且 request 會傳送

FromURI

直接在 URL後面加上 ? 以後就可以傳 Query String

留言