将带有列表的实例传递给API

时间:2018-10-13 11:27:01

标签: asp.net asp.net-web-api

有完整的测试代码。 将JSON数据发布到API时,实例人员为null。 谁能告诉我为什么

模型

public class Diploma
{
    public int PeronId { get; set; }
    public string Tile { get; set; }
    public string Organism { get; set; }
}
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Function { get; set; }
    public List<Diploma> Diplomas { get; set; }
    public Person()
    {
        Diplomas = new List<Diploma>();
    }

}

控制器

public class PersonnesController : ApiController
{
    private const string cs = "Data Source=.;Initial Catalog=test;Integrated Security=True";

    // POST : Person
    [HttpPost]
    public int Post([FromBody] Person person)
    {
        bool res = false;
        int id;
        SqlCommand cmd = new SqlCommand();
        using (SqlConnection connection = new SqlConnection(cs))
        {
            cmd = new SqlCommand("insert dbo.personnes (Name, Function) output INSERTED.ID values (@name, @function)", connection);
            cmd.Parameters.AddWithValue("@nam", person.Name);
            cmd.Parameters.AddWithValue("@function", person.Function);
            connection.Open();

            id = (int)cmd.ExecuteScalar();
            foreach (Diploma diploma in person.Diplomas)
            {
                cmd = new SqlCommand("insert diplomes values(@id, @title, @organism)", connection);
                cmd.Parameters.AddWithValue("@id", id);
                cmd.Parameters.AddWithValue("@title", diploma.Tile);
                cmd.Parameters.AddWithValue("@organism", diploma.Organism);
                cmd.ExecuteNonQuery();
            }
            return id;
        }
    }
}

我正在使用RESTClient for Firefox进行测试,

在标题部分:

Content-type : application/x-www-form-urlencoded

1 个答案:

答案 0 :(得分:2)

正在使用错误的Content-Type发送数据。

已表明数据是使用Content-type : application/x-www-form-urlencoded

发送的

而显示的数据是 JSON

{ "Name": "my name", "Function": "my function", "diplomas": [{ "title": "diploma 1", "organism": "university 1" }, { "title": "diploma 2", "organism": "university 2" }] }

将使用Content-type : application/json内容类型

模型绑定程序无法使用提供的内容类型解析内容,因此它将模型默认为 null