【问题标题】:How to POST 2 or more objects to ASP.NET Core WebAPI如何将 2 个或更多对象发布到 ASP.NET Core WebAPI
【发布时间】:2017-05-03 03:20:13
【问题描述】:

我正在尝试使用 Angular 2 将 2 个对象发布到 AspNetCore WebAPI 端点。我能够使用正文流成功提取内容。

有没有更优雅的方法来实现这一点?

[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);
    }

是否有机会将复杂的对象解析卸载到 .Net Core / WebAPI?

【问题讨论】:

  • POST 数据是什么样的?
  • [{"prop1":1234"}, {"prop2_Of_SecondObject":"1234"}]
  • 我相信模型绑定器会为您完成艰苦的工作。您应该能够向您的操作添加一个参数,该参数是用户的数组/IEnumerable。
  • 你说得对,我们可以做这样的事情。有用。 public User Complex2([FromBody]List&lt;Object&gt; temp){ return null; } 并通过 temp[0]、temp[1] 等访问它们...

标签: asp.net-core .net-core asp.net-core-webapi asp.net-core-1.1


【解决方案1】:

2 适用于希望从身体中提取多个对象的解决方案。要么参考我的问题中的前一个。或者按照大卫的建议,我们可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2015-03-08
    • 2020-11-25
    • 2012-11-14
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多