Home > OS >  .net core request list parameter always gets null
.net core request list parameter always gets null

Time:12-06

I'm trying to send a list of object in http post request to .net core app but my list in the controller always gets null. When I parse the json inside the code using JsonConvert it runs perfectly . I cant find why it doesn't bind properly to the model .

My action : public async Task<ActionResult> FileTypes([FromBody] FileTypesRequest data)

FileTypesRequest :

public class FileTypesRequest
   {
       public List<FileTypeChoice> FileTypes;
   }

FileTypeChoice:

public class FileTypeChoice
    {
        public string Content { get; set; }
        public string Type { get; set; }
    }

Postman request body:

{
    "fileTypes": [
        {
            "content": "test",
            "type": "excel"
        },
        {
            "content": "test2",
            "type": "excel"
        }
    ]
}

Any help ? Thanks !

CodePudding user response:

Enable HttpLogging Using AddHttpLogging and UseHttpLogging methods in the Startup.cs file.

You should be able to see the request body in the console log.

Most time these values are null when the case doesn't match. When you add controllers to the service configure the Json to be match case. (camel or member casing)

services.AddControllers()
    .AddJsonOptions(options =>
    {
        // ...
    });

CodePudding user response:

Ok I found the solution

public class FileTypesRequest
{
   public List<FileTypeChoice> FileTypes;
}

to

public class FileTypesRequest
{ 
   public List<FileTypeChoice> FileTypes { get; set; }
}

Made the FileTypes from variable to property.

  • Related