【问题标题】:receive complex object and handle it接收复杂对象并处理它
【发布时间】:2017-08-04 08:24:34
【问题描述】:

我正在使用asp.net web api,我的客户端在vuejs中,我传递一个带有json的对象,如下所示:

[
  {
    "key": "Table",
    "rows": 1,
    "cols": 1,
    "cells": 1
  },
  {
    "key": "Paragraph",
    "text": "asda",
    "fontSize": 14
  },
  {
    "key": "Paragraph",
    "text": "asda",
    "fontSize": 14
  },
  {
    "key": "Paragraph",
    "text": "asda",
    "fontSize": 14
  }
]

我需要在端点接收它,此时我到达端点但我的数据始终为空。

这是我的控制器:

public async Task<IHttpActionResult> CreateDocument([FromBody]DocumentDetails atributes)
{
    return Ok(atributes);
}

简单的事情,只是为了看看我是否收到数据,我创建了一个 DocumentDetails 对象,因为我收到的数据是一个列表,我有这样的东西:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace server.Models
{
    public class DocumentDetails
    {
        public int Id { get; set; }
        public List<DocumentAtributes> atributes { set; get; }
    }
}

它有一个 DocumentAtributes 类型的列表,其中应该是列表中的所有数据:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

    namespace server.Models
    {
        public class DocumentAtributes
        {
            public int Id { get; set; }
            public String key { get; set; }
            public String rows { get; set; }
            public String cols { get; set; }
            public String cells { get; set; }
            public String fontSize { get; set; }
            public String width { get; set; }
            public String height { get; set; }
            public String base64 { get; set; }
            public String align { get; set; }
            public String text { get; set; }
        }
    }

谢谢你们!

【问题讨论】:

    标签: c# asp.net asp.net-web-api controller


    【解决方案1】:

    您正在接收一个 json 数组。您的控制器应该将 List 或数组作为参数:

    public async Task<IHttpActionResult> CreateDocument([FromBody]DocumentAttributes[] atributes)
    {
        DocumentDetails details = new DocumentDetails();
        details.atributes = atributes.ToList();
        return Ok(details);
    }
    

    【讨论】:

    • 好的,现在我得到了数组,但是我没有得到里面的值,我的属性列表是空的,但是 DocumentAttributes 有数据
    • 检查我对代码所做的编辑。我认为这就是您所要求的,但并不完全确定。
    • 如果我没有属性,我无法创建它们的实例,我的意思是我收到了列表,但数组内的属性列表为空
    猜你喜欢
    • 1970-01-01
    • 2014-08-22
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多