Home > Software design >  ASP.NET Web API: how to post from a model bound to another model?
ASP.NET Web API: how to post from a model bound to another model?

Time:09-29

For my first project using C# and asp.net CORE Web-API, I'm currently struggling on a particular issue. I cannot post an item whose model is bound to another.

So I have two models, Profession and ProfessionField, which respectively contain the following code.

Profession:

{
    public class Profession
    {
        public int ProfessionId { get; set; }
 
        public string? ProfessionName { get; set; }
    }
}

ProfessionField:

{
    public class ProfessionField
    {
        public int ProfessionFieldId { get; set; }
 
        public string? ProfessionFieldName { get; set; }
 
        public Profession? Profession { get; set; }
    }
}

I would like to post a ProfessionField item in order to get something like this as a result in JSON:

{
    "professionfieldid":"1",
    "professionfieldname":"Sports",
    "profession": [
        {
            "professionid":"1",
            "professionname:"journalist"
        }
     ]
}

As a request, I have this :

[HttpPost]
public async Task<ActionResult<ProfessionField>> PostProfessionField(ProfessionField professionField)
{
    _context.ProfessionField.Add(professionField);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetProfessionField", new { id = professionField.ProfessionFieldId }, professionField);
}

I tried executing these post request in different ways with httprepl but every time, the value of "profession" was null.

Examples of requests I tried:

post -h Content-Type=application/json -c "{"professionfieldname":"Sport", "profession":"1"}"

post -h Content-Type=application/json -c "{"professionfieldname":"Sport", "profession":"1"}"

post -h Content-Type=application/json -c "{"professionfieldname":"Sport","profession": [{"professionid":"1","professionname":"journalist"}]}"

For this last one, I get an error 400, bad request, with the following comment:"The JSON value could not be converted to name_of_my_project.Models.Profession".

Do you have any idea what would be the correct request syntax or how I could improve the binding of the two models to fix this?

CodePudding user response:

I'd expect the correct JSON structure should be:

{
    "professionfieldid":"1",
    "professionfieldname":"Sports",
    "profession": {
        "professionid":"1",
        "professionname:"journalist"
    }
}

Your first two attempts are wrong because they provide a simple string "1" for the profession property, when the model is clearly expecting a complex object. The last attempt supplies an array (i.e. a list) of objects (albeit in this case there's only one thing in the list), when the model expects a single object only.

  • Related