Home > Blockchain >  C# Receiving empty object in controller
C# Receiving empty object in controller

Time:02-02

I'm trying to get some data from the request body in a POST Controller, but the console shows empty props:

The Post Controller:

[HttpPost("{id}/features")]
public ActionResult<bool> AddFeatureAsync(Guid Id, [FromBody] AddRoleFeatureRequest request)
{
   Console.WriteLine(request.Name);
   Console.WriteLine(request.Description);
   Console.WriteLine(request.Id);

   return true;
}

The AddRoleFeatureRequest class:

public class AddRoleFeatureRequest
{
    public Guid Id;
    public string? Name;
    public string? Description;
}

The JSON data from Postman (Using body raw as Json):

{
    "name": "Feature ABC",
    "description": "description",
    "id": "7e12b0ad-2c82-46f0-a69e-8538efb0aa60"
}

What am I doing wrong?

CodePudding user response:

Your "AddRoleFeatureRequest" class has capitals and your json data does not. This could be the source of your problems.

CodePudding user response:

Your properties names are not matching. Please note that json properties are cases sensitive.

You can just add JsonProperty attributes to fix this:

public class AddRoleFeatureRequest
{
    [JsonProperty("id")]
    public Guid Id;

    [JsonProperty("name")]
    public string? Name;

    [JsonProperty("description")]
    public string? Description;
}

CodePudding user response:

the attribute names might be the reasons because they ar different then the json keys, retry it while considering letters cases,

  • Related