2013-11-09 78 views
2

我正在嘗試關注教程並創建一個應用程序。我正在嘗試發出Get請求來檢索Books的列表。這是我的控制器:WebApi控制器返回空數據

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個空書本對象。

我試着向Book類中添加[Serializable]並刪除了空構造函數,但它仍然只返回一組空書。有什麼想法發生了什麼?

感謝

回答

1

你在書類的構造函數錯誤賦值語句

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

我知道這是愚蠢的東西。 TY – shek

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>