【问题标题】:Posted json not reflected in object parameter发布的 json 未反映在对象参数中
【发布时间】:2017-08-04 19:10:34
【问题描述】:

在我的 web 应用程序中,我以 json 格式发布消息对象以将其保存到数据库中。使用 Firefox 中的 devtools,我可以看到有效的 json 被发布,但是在调试服务器代码(MVC c#)时,Message 类型的参数对象有一个空的 title 和 body 属性。

打字稿中的对象定义:

export interface IMessage {
    title: string;
    body: string;
    isHidden: boolean;
}

将对象发布到服务器的代码:

public postNewMessage(message: IMessage)
{
    return this.http.postJson("/messages/newmessage", message);
}

我看到的 json 发布到网络服务器:

{"title":"title","body":"body message","isHidden":true}

服务器代码:

[HttpPost("newmessage")]
public async Task<JsonResult> Post(MessageSummary message)
{
}

Message的C#类定义

public class MessageSummary
{
    public long Id { get; set; }
    public string title { get; set; }
    public string body { get; set; }
    public author author { get; set; }
}

所以当我在服务器端设置断点时,消息对象不为空,但标题和正文属性为空。

【问题讨论】:

    标签: c# json asp.net-mvc typescript


    【解决方案1】:

    我想通了,解决方案其实很简单,只需添加 [FromBody] 我就得到了发布的对象数据:

    [HttpPost("newmessage")]
    public async Task<JsonResult> Post([FromBody] MessageSummary message)
    {
    }
    

    【讨论】:

      【解决方案2】:

      我以前从未使用过打字稿,但正文旁边的 , 不应该是 : 吗?

      export interface IMessage {
          title: string;
          body, string;
          isHidden: boolean;
      }
      

      【讨论】:

      • 这实际上只是我帖子中的错字,而不是实际代码,编辑了我的帖子。感谢您指出这一点。
      猜你喜欢
      • 2015-01-26
      • 2018-11-11
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-26
      • 1970-01-01
      相关资源
      最近更新 更多