简体   繁体   English

如何将2个或更多对象发布到ASP.NET Core WebAPI

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

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. 我正在尝试使用Angular 2将2个对象发布到AspNetCore WebAPI端点。我能够使用主体流成功提取内容。

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? 是否有机会将复杂的对象解析工作卸载到.Net Core / WebAPI?

2 Solutions for anyone looking to extract multiple objects from the body. 2解决方案,适合任何想要从身体中提取多个物体的人。 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"}]*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM