接收复杂的对象并处理它

时间:2017-08-04 08:24:35

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

我正在使用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对象,因为我收到的数据是List,我有这样的东西:

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; }
        }
    }
谢谢你们!

1 个答案:

答案 0 :(得分:2)

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

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