WebApi控制器返回空数据

时间:2013-11-09 19:43:48

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

我正在尝试按照教程创建应用。我正在尝试发送Get请求以检索Books列表。这是我的控制者:

public class BooksController : ApiController
{
    Book[] books = new Book[] 
    {
        new Book(1, "Alice In Wonderland"), 
        new Book(2, "Dune"), 
        new Book(3, "Lord of the Rings")
    };

    public IEnumerable<Book> Get()
    {
        return books;
    }
...

这是我的模特:

public class Book
{
    public Book()
    {
    }

    public Book(int id, string name)
    {
        id = this.id;
        name = this.name;
    }

    public int id { get; set; }
    public string name { get; set; }
}

在我使用空构造函数之前,它抛出了序列化错误。现在它返回空数据:

<ArrayOfBook xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApplication1.Model">
    <Book>
        <id>0</id>
        <name i:nil="true"/>
    </Book>
    <Book>
        <id>0</id>
        <name i:nil="true"/>
    </Book>
    <Book>
        <id>0</id>
        <name i:nil="true"/>
    </Book>
</ArrayOfBook>

我尝试在return books的控制器中放置一个断点,列表不是我硬编码的。这是3本空书对象。

我尝试将[Serializable]添加到Book类并删除了空构造函数,但它仍然只返回一组空书。任何想法发生了什么?

由于

2 个答案:

答案 0 :(得分:1)

Book类

的构造函数中的赋值语句错误
public Book(int id, string name)
{
    id = this.id; // reverse this assignment, and the next line as well
    name = this.name;
}

替换为

public Book(int id, string name)
{
    this.id = id; // this is the correct way
    this.name = name;
}

答案 1 :(得分:0)

陷入类似的问题。 确保您在控制器中使用的上下文指的是正确的连接字符串。

示例:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("MyConnStr", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public System.Data.Entity.DbSet<FileUpload.Models.FileTypesView> FileTypesViews { get; set; }
}

  <connectionStrings>
    <add name="MyConnStr" connectionString="data source=xxx;initial catalog=&quot;xxx&quot;;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>