问题描述
我已经在网上搜索了几个小时,并尝试了许多不同的解决方案,这些解决方案也在StackOverflow上进行了介绍.我知道以前也曾问过类似的问题,但是没有答案或评论对我有用.
I've been scouring the web for hours and tried many different solutions also described here on StackOverflow. I know similar questions have been asked before, but none of the answers or comments have worked for me.
问题:我有一个.NET Web API,该API带有一些参数的后方法.参数之一是应该从主体读取的复杂对象(即JSON).但是,此对象始终为空.
The problem: I have a .NET Web API that has a Post-method with some parameters.One of the parameters is a complex object that is supposed to be read from the body (that is JSON). However, this object is always null.
这是我的代码:
// POST api/worksheets/post_event/true/false
[Route("post_event/{newWorksheet}/{eindEvent}")]
[HttpPost]
public Event Post(bool newWorksheet, bool eindEvent, [FromBody] Event eventData)
{
return eventData;
}
要明确:eventData是始终为null的对象.布尔值可以正确读取.
To be clear: eventData is the object that's always null. The boolean values are read correctly.
完整的请求正文为:
POST http://localhost:5000/api/worksheets/post_event/true/false
Content-Type: application/json
{"Persnr":1011875, "WorksheetId":null, "Projectnr":81445, "Uursoort":8678, "Tijd":{"09-08-2016 9:25"}}
作为参考,这是事件类:
And for reference, this is the Event-class:
public class Event
{
public long Persnr { get; set; }
public int WorksheetId { get; set; }
public int Projectnr { get; set; }
public int Uursoort { get; set; }
public DateTime Tijd { get; set; }
}
我已经尝试过的一些东西:
Some of the things I've already tried:
- 将JSON更改为不同的格式(只有值,"Event":{}围绕实际对象,JSON前面是=).
- 仅使用Event参数进行测试(删除其他参数以及在路线中)
- 向事件添加默认ctor.
- 删除[FromBody]标签.如果执行此操作,则Event-object不为null,但所有属性均为null.可以通过URI填充属性,但这不是所需的行为.
根据我已阅读的所有解决方案和文档,它应该可以像上面显示的那样简单地工作.我想念什么?
According to all solutions and documentation I have read, it should simply work the way I have it displayed above.What am I missing?
推荐答案
您的json对象无效.我的建议是始终运行通过json解析器手动编写的json对象,如下所示: http://json.parser.online .fr/
Your json object is invalid. My suggestion is to always run json object written manually through a json parser like this: http://json.parser.online.fr/
"Tijd":{"09-08-2016 9:25"}
应该是
"Tijd":["09-08-2016 9:25"]
这篇关于C#Web API POST参数FromBody始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!