【问题标题】:http.post not working in Angular 5http.post 在 Angular 5 中不起作用
【发布时间】:2019-01-12 11:11:36
【问题描述】:

我正在使用 Angular 5 开发一个应用程序。

http.get 服务在这里工作正常,但在http.post 中出现问题。

下面是我的代码:

GetEmployee() {
    //Data needs to be grouped in an object array as payload
    var payload = { "StaffCode": this.employeeCode };
    this.showLoader = true;
    this.http.post<StaffInfo>(this.baseURL + 'api/StaffDetail/GetEmployee', JSON.stringify(payload)).subscribe(result => {
        this.Staff = result;
        this.showLoader = false;
    }, error => console.error(error));
}

.net 核心中的 API:

 [HttpPost("[action]")]
    public Employee GetEmployee(string StaffCode)
    {
        return util.GetEmployee(StaffCode);
    }

我在点击按钮时调用它

<button type="button" (click)="GetEmployee()" class="btn btn-sm btn-warning">Get Detail</button>

但在我的 API 中它为空。

我是否以错误的方式调用 post API?

还有一件事,如果我在参数签名之前添加[FromBody],它甚至不会命中 API。

【问题讨论】:

  • 通常,如果该端点的想法是获取员工,则最好使用 HTTP GET 请求,并通过 URL 传递 StaffCode

标签: c# angular .net-core asp.net-core-webapi


【解决方案1】:

客户端正在发送一个复杂的对象模型,但操作需要简单的字符串。

创建模型以匹配来自客户端的负载。

public class GetEmployeeModel {
    public string StaffCode { get; set; }
}

更新操作以期望帖子正文中的有效负载。

[HttpPost("[action]")]
public Employee GetEmployee([Frombody]GetEmployeeModel model) {
    return util.GetEmployee(model.StaffCode);
}

还要确保在客户端正确构建有效负载并使用正确的内容类型发送

var payload = { StaffCode: this.employeeCode };
var json = JSON.stringify(payload);
var url = this.baseURL + 'api/StaffDetail/GetEmployee';
const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/json'
    })
};
this.http.post<StaffInfo>(url, json, httpOptions).subscribe(result => {
    this.Staff = result;
    this.showLoader = false;
}, error => console.error(error));

现在理想情况下,给定动作的名称和预期的功能,您最好将动作重构为 HTTP GET 请求,在路由中传递代码

[HttpGet("[action]/{StaffCode}")]
public Employee GetEmployee(string StaffCode)
{
    return util.GetEmployee(StaffCode);
}

并相应地更新客户端以发出请求

var url = this.baseURL + 'api/StaffDetail/GetEmployee/' + this.employeeCode;
this.http.get<StaffInfo>(url).subscribe(result => {
    this.Staff = result;
    this.showLoader = false;
}, error => console.error(error));

【讨论】:

  • 谢谢,我会尝试,但如果我想发布一个字符串,我该怎么办?
  • @Jack 使用一个简单的对象。您将发布JSON.stringify(this.employeeCode) 并将操作参数保留为字符串。
  • 您的建议在 api 中使用 [HttpGet("[action]/{StaffCode}")] 作为获取有效,但在 httppost JSON.stringify(this.employeeCode) 中不起作用,仍然空
  • 别忘了 from body 属性
  • 如果我添加 [FromBody] 而不是“服务器响应状态为 415 ()”
猜你喜欢
  • 2017-09-14
  • 2017-06-20
  • 2018-01-09
  • 2014-05-26
  • 2016-12-17
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 2018-09-17
相关资源
最近更新 更多