2

我正在尝试遵循教程并创建一个应用程序。我正在尝试发出获取请求以检索书籍列表。这是我的控制器:

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 类并删除空构造函数,但它仍然只返回一组空书籍。任何想法发生了什么?

谢谢

4

2 回答 2

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;
}
于 2013-11-09T19:47:37.243 回答
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>
于 2017-01-13T16:24:31.957 回答