pQuestions123
pQuestions123

Reputation: 4611

.NET core WebAPI weird body in POST. Not serializing correctly?

I have a very simple post method:

[HttpPost]
        public IActionResult Post(AgreementType model)
        {
            var ag = _facade.AddOrUpdateAgreement(model);
            return Json(ag);
        }

and trying to send some test calls against it to see if it is coming through ok. It is not. I have checked the network tab in the browser as well as fiddler and the request definitely looks ok to me. (Content-Type is application/json and the body is there just fine).

I placed a break point inside the server side post method and it is getting to the method and the structure of model is ok just all the strings are null and arrays are empty.

It feels like a serialization issue, looks like I am just getting an empty (new) AgreementType model instead of the one coming up...

Edit: Here is the json and the C# Model:

json:

{
   "QuestionCategories": [1],
   "Id": 1,
   "Name": "Name",
   "ShortName": "Short Name"
 }

Model:

namespace DTModels.Models
{
   public class AgreementType
   {
       public virtual ICollection<QuestionCategory> QuestionCategories { get; set; }

       public AgreementType()
       {
           QuestionCategories = new HashSet<QuestionCategory>();
       }

       public int Id { get; set; }
       public string Name { get; set; }
       public string ShortName { get; set; }
   }
}

Upvotes: 2

Views: 1670

Answers (2)

Anil Goel
Anil Goel

Reputation: 271

In your c# object QuestionCategories is a collection of QuestionCategory, but in your json you are sending a collection of int. That will not map. YourJson need to be something like

{
   "QuestionCategories": [
                          {"prop1" : "value",
                           "prop2": "value"},
                          {"prop1": "value",
                           "prop2": "value"}
                         ],
   "Id": 1,
   "Name": "Name",
   "ShortName": "Short Name"
 }

Where prop1 and prop2 are properties of QuestionCategory and my example is passing 2 objects in the collection. Also you need to set the content-type in your header to be application/json.

Upvotes: 2

pQuestions123
pQuestions123

Reputation: 4611

Figured it out. Make sure your content-length is set!

Upvotes: 0

Related Questions