我正在使用 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。
最佳答案
客户端正在发送一个复杂的对象模型,但操作需要简单的字符串。
创建模型以匹配来自客户端的负载。
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));
关于c# - http.post 在 Angular 5 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51691586/