Search code examples
c#phprestasp.net-mvc-4

Map PHP named array to C# controller parameter


I have a third party API with documentation for PHP, but I'm using C# and ASP.NET MVC.

One of API methods send as parameter Fields.

FIELDS is an array that contains field ID where int value is stored.

So in PHP it will be something like:

$fields=array(ID=>4);

What is the best way to get such a parameter to controller method in C#?

I'm doing it like this:

public class FieldsModel
{
    public int ID { get; set; }
}

[HttpPost]
public string Test(FieldsModel[] FIELDS)
{
   //some code goes here
}

This code is working, but maybe there is a better solution to map PHP named array to a C# controller parameter?

P.S. Actually FIELDS array always contains only one ID if it matters.


Solution

  • Due to php arrays can be used as key,value data structure, when it is serialized to JSON you get something similar to:

    {
      "ID": 4
    }
    

    The easiest way to manage it in C# (knowing that C# is mainly used to write Object Oriented code), is to parse that JSON into an object, that contains a property for each JSON key. You can also, change use fields instead of properties like this:

    public class FieldsModel
    {
        public int ID;
    }
    

    However the second approach isnt' recommended.

    I think that you are only going to get a "Field", so you can rewrite your Test endpoint to wait for a single FieldsModel, like this:

    [HttpPost]
    public string Test(FieldsModel fields)
    {
       //some code goes here
    }