简体   繁体   中英

Web API - Accepting array urlencoded parameters

I have built a Web API that 90% functions. Where I'm stuck is on how to accept jQuery style array encoded parameters using Web API. Here is my GET request:

GET /api/v1/Trades?take=3&skip=0&page=1&pageSize=3&sort%5B0%5D%5Bfield%5D=tradeName&sort%5B0%5D%5Bdir%5D=asc

Unencoded, the request looks like this:

GET /api/v1/Trades?take=3&skip=0&page=1&pageSize=3&sort[0][field‌​]=tradeName&sort[0][‌​dir]=asc

This style is consistent with how jQuery's $.param method serializes requests. How do I accept this as a parameter in Web API? I've tried the following:

[System.Web.Http.HttpGet]
[System.Web.Http.Route("api/v1/Trades")]
public IHttpActionResult GetTrades(int page = -1, int pageSize = -1, int skip = -1, int take = -1, string[,] sort = null)
{
    // Do stuff ...
}

In this instance, my method receives a 500 error with the following message:

Optional parameter 'sort' is not supported by 'FormatterParameterBinding'.

I've also tried this:

public IHttpActionResult GetTrades(string[,] sort, int page = -1, int pageSize = -1, int skip = -1, int take = -1)
{
    // Do stuff ...
}

Using this, my method gets called, but sort is always null . I've also tried it more generic, like this:

public IHttpActionResult GetTrades(object sort, int page = -1, int pageSize = -1, int skip = -1, int take = -1)
{
    // Do stuff ...
}

Again, my method gets called, but sort is always null .

Any suggestions would be helpful!

If you are sending This many parameters then it is good practice to use POST method, in that you can send data in Object.

Still if you want to use GET method then use

[System.Web.Http.HttpGet]
[System.Web.Http.Route("api/v1/Trades")]
public IHttpActionResult GetTrades(int page = -1, int pageSize = -1, int skip = -1, int take = -1, string sort = "")
{
    // Do stuff ...
}

AND doing API call

GET /api/v1/Trades?take=3&skip=0&page=1&pageSize=3&sort=tradeName asc,Col2 desc

After getting call in GetTrades method split sort string data by comma(,) and then by space( ). So you will get column names and sort order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM