首页 > 解决方案 > 发布到 Asp.Net Core 收到空对象

问题描述

我正在从我的 Angular 7 应用程序向 AspNet Core 后端服务器发出 POST 请求。但是,当接收模型时,它是空的。

我正在使用 Postman 进行测试,并且在使用 Postman 时它可以工作。但是从客户端应用程序发送时它不起作用。

这是我的控制器和控制器基础:

public class BaseController : ControllerBase {
    public readonly ILogger _logger;
}
[Route("api/[controller]")]
public class ExperienceController : BaseController {
    [HttpPost, Route("Create")]
    public async Task<IActionResult> Create([FromBody] Experience experience){
      // code ommited
    }
}

这是我的 service.ts 代码

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
// some code omitted

saveExperience(experience: Experience): Observable<Experience> {
  let url = `${this.baseUrl}/Experience/Create`;
  return this.http.post<Experience>(url, experience, httpOptions).pipe(
    tap((newExp: Experience) => this.log(`Created experience ${newExp}`)),
    catchError(this.handleError<Experience>('saveExperience'))
  );
}

客户要求

从我的客户端应用程序发送的对象使用的是驼峰式属性,而后端的模型使用的是 pascal-case。在 Postman 中,这不会影响任何事情,但以防万一。 邮递员请求

我真的很困惑为什么从邮递员那里打电话时它正在工作。但是来自客户端的每次测试,我都会收到一个空对象。

编辑#1 我从我的 Experience 类中删除了所有字段,只使用了名称和描述,它起作用了,我只是发现如果我有一个复杂的属性,我就会遇到这个问题。我添加了一个默认构造函数,初始化属性但仍然遇到同样的问题。请注意,我只有在使用 Angular 应用程序时才会遇到这个问题,如果我使用 Postman,它就可以工作

public class Experience : ExperienceBase {
    public string Name { get; set; }
    public string Description { get; set; }

    // this guy here is causing the issue
    public LocationDetails LocationDetails { get; set; } 

}

提前致谢

标签: c#angulartypescriptasp.net-core

解决方案


推荐阅读