好吧,我遇到了ASP.NET Web API的問題。我遵循this關於如何創建它的教程。爲了達到我的目的,我爲了教程做了修改。ASP.NET Web API返回json響應中的空集合
我有一個補丁類,它有一個下載URL的集合。 API正在返回所有信息,只有DownloadURL的集合返回爲null。 但是,當我逐步調試代碼時,它正確地返回了集合。 我做錯了什麼。我無法找到我的錯誤。 這裏是型號:
public class Patch
{
[Key]
[Required]
[JsonProperty("PatchVersion")]
public string PatchVersion { get; set; }
[Required]
[JsonProperty("Length")]
public long Length { get; set; }
[JsonProperty("VersionToUpdateFrom")]
public string VersionToUpdateFrom { get; set; }
[JsonProperty("DownloadUris")]
public ICollection<DownloadUri> DownloadUris { get; set; }
}
public class DownloadUri
{
[Key]
[Required]
[JsonProperty("AbsolutePath")]
public string AbsolutePath { get; set; }
[Required]
[JsonProperty("IndirectDownload")]
public bool IndirectDownload { get; set; }
}
這是我的DataContext類:
public class PatchesContext : DbContext
{
public PatchesContext()
: base("name=PatchesContext")
{
}
public DbSet<Patch> Patches { get; set; }
public DbSet<DownloadUri> DownloadUris { get; set; }
}
這是ContextInitializer
public class PatchesContextInitializer : DropCreateDatabaseIfModelChanges<PatchesContext>
{
protected override void Seed(PatchesContext context)
{
var downloadUri = new List<DownloadUri>
{
new DownloadUri
{
AbsolutePath = "http://downloadUri1.test", IndirectDownload = false
},
new DownloadUri
{
AbsolutePath = "http://downloadUri2.test", IndirectDownload = false
}
};
var patches = new List<Patch>
{
new Patch
{
Length = 100000, PatchVersion = "1.0.0.0", VersionToUpdateFrom = string.Empty, DownloadUris = downloadUri
},
new Patch
{
DownloadUris = null, Length = 10000, PatchVersion = "1.1.0.0", VersionToUpdateFrom = "1.0.0.0"
}
};
patches.ForEach(p => context.Patches.Add(p));
context.SaveChanges();
}
}
最後這裏是我的控制器類。我離開了POST,PUT和DELETE方法,因爲我(如果得到的是不工作沒有意義)沒有測試他們尚未:
public class AdminController : ApiController
{
private PatchesContext db = new PatchesContext();
// GET api/Admin
public IEnumerable<Patch> GetPatches()
{
return db.Patches.AsEnumerable();
}
// GET api/Admin/5
public Patch GetPatch(string version)
{
Patch patch = db.Patches.Find(version);
if (patch == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return patch;
}
}
我希望你們能幫助我和感謝。
/編輯: 的標題是這樣的:
Status Code: 200 OK
Cache-Control: no-cache
Content-Length: 291
Content-Type: application/json; charset=utf-8
Date: Fri, 25 Oct 2013 17:25:48 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/8.0
X-SourceFiles: =?UTF-8?B?RTpcVXNlcnNcUm9iZXJ0XERvY3VtZW50c1xWaXN1YWwgU3R1ZGlvIDIwMTJcUHJvamVjdHNcTjQ0V2Vic2l0ZVxONDRXZWJzaXRlXGFwaVxhZG 1pbg==?=
響應主體看起來是這樣的:
[
{
"$id": "1",
"PatchVersion": "1.0.0.0",
"Length": 100000,
"VersionToUpdateFrom": "",
"DownloadUris": null
},
{
"$id": "2",
"PatchVersion": "1.1.0.0",
"Length": 10000,
"VersionToUpdateFrom": "1.0.0.0",
"DownloadUris": null
}
]
所以你獲得了200個成功的代碼,但沒有數據?當您在Web API操作中放置斷點時,是否返回了非空的內容? –
我們可以看到json的例子嗎? – AJP
我將響應標題和正文添加到我的初始文章 – Ruhrpottpatriot