How to POST 2 or more objects to ASP.NET Core WebAPI

413 views Asked by At

I am trying to POST 2 objects to an AspNetCore WebAPI endpoint using Angular 2. I am able to extract the content successfully using the body stream.

Is there a more elegant way of achieving this?

[HttpPost]
    [ActionNameAttribute("complex2objects")]
    public User ComplexTwoObjects(){
        var body = Helpers.Request.ExtractBody(this.Request.Body);
        var obj1 = Helpers.Request.GetBodyObject(body,0,new User());
        var obj2 = Helpers.Request.GetBodyObject(body,1,new User());

        return obj2;
    }
    ...

    public static string ExtractBody(Stream body){
        StreamReader reader = new StreamReader(body);
        return reader.ReadToEnd();
    }
    public static T GetBodyObject<T>(string content, int index,T type){
        var composite = JsonConvert.DeserializeObject<IList>(content);
        return JsonConvert.DeserializeAnonymousType(composite[index].ToString(),type);
    }

Is there a chance to offload the complex object parsing to .Net Core / WebAPI?

1

There are 1 answers

0
Tony On

2 Solutions for anyone looking to extract multiple objects from the body. Either refer to the top one in my question. Or as David suggested, we can do something like this:

    [HttpPost]
    [ActionNameAttribute("complex2")]
    public User Complex2([FromBody]List<Object> temp){            
        return new User(); 
    }
/*Input JSON Array:
 [{"Username":"inputAAAA","Password":"1234"},{"Property_In_Object2":"123123"}]*/