asp.net core - Error Passing Object With Generic List To Controller - Stack Overflow

I am trying to create a method called CreateContact on my Contacts Controller:Here is my controller:[

I am trying to create a method called CreateContact on my Contacts Controller:

Here is my controller:

[Route("api/[controller]/[action]")]
[ApiController]
public class ContactController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateContact([FromBody] ContactEntity myContact)
    {
        return Ok();
    }
}

And here is the ContactEntity class

public class ContactEntity : _EntityBase
{
    private string _FirstName;
    public string FirstName
    {
        get { return _FirstName; }
        set
        {
            SetProperty(nameof(FirstName), ref _FirstName, value);
        }
    }

    private string _MiddleName;
    public string MiddleName
    {
        get { return _MiddleName; }
        set
        {
            SetProperty(nameof(MiddleName), ref _MiddleName, value);
        }
    }

    private string _LastName;
    public string LastName
    {
        get { return _LastName; }
        set
        {
            SetProperty(nameof(LastName), ref _LastName, value);
        }
    }

    private string _CompanyName = "";
    public string CompanyName
    {
        get { return _CompanyName; }
        set
        {
            SetProperty(nameof(CompanyName), ref _CompanyName, value);
        }
    }

    private string _Title = "";
    public string Title
    {
        get { return _Title; }
        set
        {
            SetProperty(nameof(Title), ref _Title, value);
        }
    }

    private string _Suffix = "";
    public string Suffix
    {
        get { return _Suffix; }
        set
        {
            SetProperty(nameof(Suffix), ref _Suffix, value);
        }
    }
        
    private string _DisplayName = "";
    public string DisplayName
    {
        get { return _DisplayName; }
        set
        {
            SetProperty(nameof(DisplayName), ref _DisplayName, value);
        }
    }

    private string _Tags;
    public string Tags
    {
        get { return _Tags; }
        set
        {
            SetProperty(nameof(Tags), ref _Tags, value);
        }
    }

    private string _Notes;
    public string Notes
    {
        get { return _Notes; }
        set
        {
            SetProperty(nameof(Notes), ref _Notes, value);
        }
    }

    public List<ContactEmailEntity> ContactEmails { get; set; }

    public ContactEntity()
    {
        ContactEmails = new List<ContactEmailEntity>();
    }
}

When I run this using Swagger and click "Try It Out", this is what I send:

{
  "isDirty": true,
  "id": 0,
  "createdDT": "2025-03-04T06:35:21.321Z",
  "createdByID": 0,
  "deletedDT": "2025-03-04T06:35:21.321Z",
  "deletedByID": 0,
  "modifiedDT": "2025-03-04T06:35:21.321Z",
  "modifiedByID": 0,
  "firstName": "string",
  "middleName": "string",
  "lastName": "string",
  "companyName": "string",
  "title": "string",
  "suffix": "string",
  "displayName": "string",
  "tags": "string",
  "notes": "string",
  "contactEmails": [
    {
      "isDirty": true,
      "id": 0,
      "createdDT": "2025-03-04T06:35:21.321Z",
      "createdByID": 0,
      "deletedDT": "2025-03-04T06:35:21.321Z",
      "deletedByID": 0,
      "modifiedDT": "2025-03-04T06:35:21.321Z",
      "modifiedByID": 0,
      "title": "string",
      "emailAddress": "[email protected]",
      "contactId": 0,
      "contact": "string"
    }
  ]
}

and this is the error I get in the response body when I click Execute. The API method is not called. My breakpoint in the controller is not hit.

{
  "type": ".5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-093143ebe720ffa8f95048231e2a7411-87485704fc9c556a-00",
  "errors": {
    "myContact": [
      "The myContact field is required."
    ],
    "$.contactEmails[0].contact": [
      "The JSON value could not be converted to Falcon.Shared.Entities.ContactEntity. Path: $.contactEmails[0].contact | LineNumber: 31 | BytePositionInLine: 25."
    ]
  }
}

If I take the ContactEmails property off the ContactEntity, then it works fine. The API method is called and my breakpoint in the controller is hit.

Anyone see what's wrong here?

I am trying to create a method called CreateContact on my Contacts Controller:

Here is my controller:

[Route("api/[controller]/[action]")]
[ApiController]
public class ContactController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateContact([FromBody] ContactEntity myContact)
    {
        return Ok();
    }
}

And here is the ContactEntity class

public class ContactEntity : _EntityBase
{
    private string _FirstName;
    public string FirstName
    {
        get { return _FirstName; }
        set
        {
            SetProperty(nameof(FirstName), ref _FirstName, value);
        }
    }

    private string _MiddleName;
    public string MiddleName
    {
        get { return _MiddleName; }
        set
        {
            SetProperty(nameof(MiddleName), ref _MiddleName, value);
        }
    }

    private string _LastName;
    public string LastName
    {
        get { return _LastName; }
        set
        {
            SetProperty(nameof(LastName), ref _LastName, value);
        }
    }

    private string _CompanyName = "";
    public string CompanyName
    {
        get { return _CompanyName; }
        set
        {
            SetProperty(nameof(CompanyName), ref _CompanyName, value);
        }
    }

    private string _Title = "";
    public string Title
    {
        get { return _Title; }
        set
        {
            SetProperty(nameof(Title), ref _Title, value);
        }
    }

    private string _Suffix = "";
    public string Suffix
    {
        get { return _Suffix; }
        set
        {
            SetProperty(nameof(Suffix), ref _Suffix, value);
        }
    }
        
    private string _DisplayName = "";
    public string DisplayName
    {
        get { return _DisplayName; }
        set
        {
            SetProperty(nameof(DisplayName), ref _DisplayName, value);
        }
    }

    private string _Tags;
    public string Tags
    {
        get { return _Tags; }
        set
        {
            SetProperty(nameof(Tags), ref _Tags, value);
        }
    }

    private string _Notes;
    public string Notes
    {
        get { return _Notes; }
        set
        {
            SetProperty(nameof(Notes), ref _Notes, value);
        }
    }

    public List<ContactEmailEntity> ContactEmails { get; set; }

    public ContactEntity()
    {
        ContactEmails = new List<ContactEmailEntity>();
    }
}

When I run this using Swagger and click "Try It Out", this is what I send:

{
  "isDirty": true,
  "id": 0,
  "createdDT": "2025-03-04T06:35:21.321Z",
  "createdByID": 0,
  "deletedDT": "2025-03-04T06:35:21.321Z",
  "deletedByID": 0,
  "modifiedDT": "2025-03-04T06:35:21.321Z",
  "modifiedByID": 0,
  "firstName": "string",
  "middleName": "string",
  "lastName": "string",
  "companyName": "string",
  "title": "string",
  "suffix": "string",
  "displayName": "string",
  "tags": "string",
  "notes": "string",
  "contactEmails": [
    {
      "isDirty": true,
      "id": 0,
      "createdDT": "2025-03-04T06:35:21.321Z",
      "createdByID": 0,
      "deletedDT": "2025-03-04T06:35:21.321Z",
      "deletedByID": 0,
      "modifiedDT": "2025-03-04T06:35:21.321Z",
      "modifiedByID": 0,
      "title": "string",
      "emailAddress": "[email protected]",
      "contactId": 0,
      "contact": "string"
    }
  ]
}

and this is the error I get in the response body when I click Execute. The API method is not called. My breakpoint in the controller is not hit.

{
  "type": "https://tools.ietf./html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-093143ebe720ffa8f95048231e2a7411-87485704fc9c556a-00",
  "errors": {
    "myContact": [
      "The myContact field is required."
    ],
    "$.contactEmails[0].contact": [
      "The JSON value could not be converted to Falcon.Shared.Entities.ContactEntity. Path: $.contactEmails[0].contact | LineNumber: 31 | BytePositionInLine: 25."
    ]
  }
}

If I take the ContactEmails property off the ContactEntity, then it works fine. The API method is called and my breakpoint in the controller is hit.

Anyone see what's wrong here?

Share asked Mar 4 at 6:40 CoderForHireCoderForHire 4631 gold badge13 silver badges35 bronze badges 1
  • I believe the mentioned ContactEmails and Contact are the properties that used for associated entity(s). Would recommend to use DTO (Data Transfer Object) that only includes the property/field that needed to sent from front end. Then use DTO to map to entity. – Yong Shun Commented Mar 4 at 7:52
Add a comment  | 

1 Answer 1

Reset to default 0

Good practice when sending the data between front-end and back-end is working with Data Transfer Object instead of entity.

This will get rid of those properties especially for the associated entity(s) which is not required to be provided from the front-end.

  1. In your DTO, you should define the property that is needed during insertion of ContactEntity. For example:
public class CreateContactInput
{
    [Required]  // Specify the data annotation attribute for property validation
    public string FirstName { get; set; }

    public string MiddleName { get; set; }

    public string LastName { get; set; }

    public string CompanyName { get; set; }

    public string Title { get; set; }

    public string Suffix { get; set; }
        
    public string DisplayName { get; set; }

    public string Tags { get; set; }

    public string Notes { get; set; }

    public string EmailAddress { get; set; }
}
  1. Your API action should expect to receive the request body with CreateContactInput type.

  2. You need to map the data from CreateContactInput to ContactEntity before inserting into DB (via Entity Framework). You may consider for the mapping library such as AutoMapper, Mapster etc.

[HttpPost]
public IActionResult CreateContact([FromBody] CreateContactInput input)
{
    // Map CreateContactInput to ContactEntity
    ContactEntity contact = new ContactEntity 
    {
        Name = input.Name,
        ..., // For other properties
        ContactEmails = new List<ContactEmailEntity>
        {
            new ContactEmailEntity
            {
                EmailAddress = input.EmailAddress
            }
        }
    };

    // Insert ContactEntity to DB

    return Ok();
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745058785a4608834.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信