2

I am newbie to WEB API2 and JSON overall. I have a JSON body like this

{
  "Input_data": {
     "method": "check",
     "hashcode": " xxxxxx ",
     "accountId": "11111111",
  }
}

How could I retrieve values from POST request?

I have model like this

 [JsonArray]
 public class BaseInput
 {       
    [JsonProperty(PropertyName = "method")]
    public  string Method { get; set; }

    [JsonProperty(PropertyName = "hashcode")]
    public string hashCode { get; set; }

    [JsonProperty(PropertyName = "accountid")]
    public int accountId { get; set; }
}

And controller code like this

BaseOutput ApiReqeust(int partnerId,[FromBody] BaseInput Input_data)

And Input_data is always null.

What am I doing wrong?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
So_oP
  • 1,211
  • 15
  • 31

2 Answers2

4

You are using the wrong model for that JSON input

This more matches your JSON model

public class InputData {
    [JsonProperty("method")]
    public string method { get; set; }

    [JsonProperty("hashcode")]
    public string hashcode { get; set; }

    [JsonProperty("accountId")]
    public string accountId { get; set; }
}

public class BaseInput {
    [JsonProperty("Input_data")]
    public InputData Input_data { get; set; }
}

the controller code appears to be fine as it is.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
1

Aside from the matching parameter name problem that @Nkosi mentioned, I believe you have another issue with your JSON parameters aligning with your controller declaraction. When passing a JSON payload to the API controller, the model binding that is built into WEB API will not recognize the BaseInput Input_data as an expected value. To account for this, your JSON should look like:

{
    "method": "check",
    "hashcode": " xxxxxx ",
    "accountId": "11111111"
}

Also, for POST methods, it is best not to use URL variables in your parameter list on the controller. You can include any variables that are needed with the rest of your JSON data. So your controller would look like this:

BaseOutput ApiReqeust(BaseInput Input_data)

Your BaseInput model would look like this:

public class BaseInput
{       
    [JsonProperty(PropertyName = "partnerId")]
    public  int partnerId { get; set; }

    [JsonProperty(PropertyName = "method")]
    public  string method { get; set; }

    [JsonProperty(PropertyName = "hashcode")]
    public string hashCode { get; set; }

    [JsonProperty(PropertyName = "accountid")]
    public int accountId { get; set; }
}

And your JSON data would ultimately look like this:

{
    "partnerId": 1,
    "method": "check",
    "hashcode": " xxxxxx ",
    "accountId": "11111111"
}

I also agree with the comments that you do not need the [JsonArray] attribute as you are not passing any arrays.

Luke T Brooks
  • 545
  • 1
  • 8
  • 25