【发布时间】:2017-09-18 11:50:02
【问题描述】:
我对 Angular 2 英雄教程进行了重新编程,使其在带有 Web API 的 ASP.NET Web 应用程序中运行,并与该 Web API 而不是内存中的 Web API 进行通信。 一切正常。只剩下一个问题:
在 ASP.NET 的服务环境和 Angular 环境中,我使用对象 Hero。 C# 对象中属性的命名约定是以大写字母开头的属性名。 JS 中的命名约定是以小写开头的属性名。我更喜欢在我的编码中遵循这个约定。 如果我这样做,对象当然不会在接收站点正确反序列化。 这个一般是怎么处理的?
ASP.NET 控制器中的 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;}
webservice 为 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 个对象,只显示记录的内容。像这样:
【问题讨论】:
-
根据我的经验,从 c# 到 Angular 的属性映射不区分大小写。只要属性的拼写正确,就不会有任何问题。你有什么错误吗?
-
不区分大小写?有趣的。回答您的问题:我没有收到任何错误。它只返回浏览器中的 6 个对象,只显示记录的内容。这意味着对象被反序列化,只有属性不匹配。
标签: c# angular web-services asp.net-web-api naming-conventions