我对 Angular 2 英雄教程进行了重新编程,以便它在具有 Web API 的 ASP.NET Web 应用程序中运行,并与该 Web API 而不是内存中的 Web API 进行通信。 一切正常。只剩下一个问题:
在 ASP.NET 的服务环境和 Angular 环境中,我使用对象 Hero。 C# 对象中属性的命名约定是以大写字母开头的属性名称。 JS 中的命名约定是属性名以小写开头。我更喜欢在我的编码中遵循这个约定。 如果我这样做,对象当然不会在接收站点上正确反序列化。 通常如何处理?
ASP.NET Controller 中的get(数组):
// GET api/heroes
public HttpResponseMessage Get()
{
String heros = JsonConvert.SerializeObject(GetHeroes().ToArray<Hero>());
return new HttpResponseMessage()
{
Content = new StringContent(heros, System.Text.Encoding.UTF8, "application/json")
};
}
GetHeroes() 返回英雄列表:
public class Hero
{
public int id { get; set; }
public string name { get; set; }
}
hero.service.ts 中的代码:
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json() as Hero[])
.catch(this.handleError); }
最后是 hero.ts 中的英雄类:
export class Hero { id: number; name: string;}
网络服务为 get 提供的原始代码是:
[{"id":0,"name":"Zero"},{"id":11,"name":"Mr. Nice"},{"id":12,"name":"Narco"},{"id":13,"name":"Bombasto"},{"id":14,"name":"Celeritas"},{"id":15,"name":"Magneta"}]
问题是我怎样才能在 C# 中继续使用(这现在会导致问题)
public class Hero
{
public int Id { get; set; }
public string Name { get; set; }
}
如果我这样做,我不会收到任何错误。它只返回浏览器中的6个对象,只返回记录的内容,不显示。像这样:
最佳答案
试试这个
public class Hero
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
关于c# - 将 C# ASPNET WebApi 对象的属性映射到 Angular 2,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46278554/