skip to Main Content

my c# api takes two parameters, one complex object and one string:

[HttpPost, Route("paramtester")]
public string paramtester(people user, string message) {
    return user.name + message;}

how do I pass by a json object in the body? I have tried passing in a serial json object which doesn’t work at all:

{
    "user": {
        "name": "John Doe",
        "age": 30,
        "country": "USA"
    },
    "message": "Hello, World!"
}

this will return:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-40ce97917410bdcff73bb4d8737ed944-2c7f4bf20348d6b7-00",
    "errors": {
        "name": [
            "The name field is required."
        ],
        "address": [
            "The address field is required."
        ],
        "message": [
            "The message field is required."
        ]
    }
}

2

Answers


  1. You should create a DTO (Data Transfer Object) that includes both:

        public sealed class MyDto
        {
            [JsonPropertyName("user")]
            public User user { get; set; }
    
            [JsonPropertyName("message")]
            public string message { get; set; }
        }
    
        public sealed class User
        {
            [JsonPropertyName("name")]
            public string name { get; set; }
    
            [JsonPropertyName("age")]
            public int age { get; set; }
    
            [JsonPropertyName("country")]
            public string country { get; set; }
        }
    

    Then add [FromBody] to the endpoint:

    [HttpPost, Route("paramtester")]
    public string paramtester([FromBody] MyDto myDto) {
        return myDto.Name + myDto.Message;}
    
    Login or Signup to reply.
  2. There is 2 correct approaches:

    1. create a request object that contains a complex object user and a silple string message

      public class ParamTesterRequest
      {
         public People User {get; set;}
         public string Message {get; set;}
      }
      

      So your web API become

       [HttpPost("paramtester")]
       public string ParamTester(ParamTesterRequest request)
       {
          return request.User.Name + request.Message;
       }
      
    2. the other one is as said by Selvin, use the complex parameter user from body and the other one as query parameter. So your web API become

       [HttpPost("paramtester")]
       public string ParamTester([FromQuery] string message, [FromBody] People user)
       {
          return user.Name + message;
       }
      

    NOTE: the first answer is that it is the simplest and cleanest

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search