1

I"m using WebAPI with MVC4, doing a http get that looks like this:

api_version=2&products=[{"id":97497,"name":"iPad"}]&pageno=1

The signature of the get action controller that maps to this call is:

[HttpGet]
public string Get([FromUri] ProductRequest request){ ... }

The problem is that the ProductRequest object passed into the Get action method above contains nulls for products, while all other values are Ok.

So it seems that it has trouble converting products=[{"id":97497,"name":"iPad"}] into the right object type, which is defined as:

public IEnumerable<Products> products { get; set;} in ProductRequest model and Products class looks like:

public int id { get; set; }
public string name { get; set; }

As, an additional information, when using the same call with a POST instead of a GET, it works fine, the object is converted properly.

So, what am I doing wrong, how can I get http GET to properly convert the query parameters to the model passed in?

aizaz
  • 2,948
  • 9
  • 23
  • 55
IIS7 Rewrite
  • 727
  • 3
  • 13
  • 28

2 Answers2

0

I think you confused between HTTP POST and HTTP GET that's why you did get the product as null. You could have a look at What's the difference between GET and POST

Basically, I think you could use TempData but it has pros and cons and depend on the context how you use it.

Community
  • 1
  • 1
cat_minhv0
  • 1,326
  • 10
  • 18
0

You can do it through the url, but you don't use JSON. Here's what your URL should look like:

api_version=2&products[0].id=97497&products[0].name=iPad&pageno=1

If you wanted to add more products in the same request, you would increment the array index:

{urlasabove}&products[1].id=4234&products[1].name=iPadmini

This is fine for your request, but can quickly get out of hand. For a complex object in a GET request you may consider using a POST instead. Or, you could include the parameters in the GET body but that's not necessarily the best idea. See discussion on this SO question.

Community
  • 1
  • 1
Simon C
  • 9,008
  • 3
  • 33
  • 53