将多个对象发布到Web API

编程入门 行业动态 更新时间:2024-10-25 14:27:20
本文介绍了将多个对象发布到Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用JSON对象将数据传递到我的Web API.发送单个对象似乎可以正常工作,但是一旦我输入了第二个参数,第二个对象似乎甚至无法在服务器端初始化?

I am trying to pass data to my web API using JSON objects. Sending a single object does seems to work fine but as soon as I put a second parameter, the second object does not even seems to initialize on the server side?

请查看下面的代码,以查看我如何处理数据参数

Please view the code below to see how I am handling the data parameter

[HttpPost("")] public JsonResult Post([FromBody]Log_Header headerData, [FromBody]Log_Detail detailData) { return Json("Test"); }

上面的每个类都有简单的字符串数据,例如下面的类:

Each of the classes above have simple string data, eg of class below:

public class Log_Header { public int Id { get; set; } public string Name{ get; set; } }

正在发送的数据示例:

var header = { Id: 0, Name: "Test 3", } var detail = { Id: 0, Desc: "Test 1", } $http({ method: 'POST', url: "api/addLog", data : { header: header, detail: detail } })

这仅仅是演示数据.

我尝试过几种不同的方式发送数据,例如:

I have tried sending the data up in few different ways e.g below:

var data = { Id: 0, Name: "Test 3", LogID: 0, Desc: "Test", }

但是似乎什么都无法正常工作,我猜我在错误地设置了Web API?

But nothing seems to get this working, I'm guessing I am setting up the web API incorrectly?

总体而言,问题是[FromBody]Release_Log_Detail detailData根本不接收任何数据,并且从断点查看对象时,它显示为null.

Overall, the problem is [FromBody]Release_Log_Detail detailData does not receive any data at all and when viewing the object from a breakpoint it appears as null.

如果有人有任何想法,请在下面发表评论或回答.如果您需要我的更多信息,请询问.

if anyone has any ideas please leave a comment or answer below. If you need anymore information from me please ask.

推荐答案

无论我们从angular $ http发布什么内容,它都会考虑单个对象,因此我们需要在服务器上的单个对象中读取它

Whatever we post from angular $http, it consider a single object, so we need to read it in a single object on server

我们可以这样做

[HttpPost("")] public JsonResult Post([FromBody]PostData data) { return Json("Test"); } class PostData { public Log_Header LogHeader { get; set; } public Log_Detail LogDetail { get; set; } }

角柱

$http({ method: 'POST', url: "api/addLog", data : { LogHeader : header, LogDetail : detail } })

更多推荐

将多个对象发布到Web API

本文发布于:2023-10-12 01:22:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483355.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   对象   API   Web

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!