c# - http.post 在 Angular 5 中不起作用

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

我正在使用 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 中它是空的。

enter image description here

我是否以错误的方式调用了 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/

相关文章:

c# - 如果创建了一个未显示的窗口,应用程序不会退出

angular - Angular 中的 ReactiveFormsModule 无法与 [formGroup] 一起使用(我到处都看过)

c# - Service Fabric 本地集群设置问题

c# - 使用 C# 和 InsertParameters (ASP.NET) 没有时间的日期

javascript - 将 ReadonlyArray<any> 转换为普通的可变数组 []?

Angular "let-col"没有传递所有属性

c# - 将参数发布到 api 主体返回错误 403

c# - 当线程已经终止(.NET 5/Core)时,Thread.Join 方法并不总是返回相同的值

json - NewtonSoft 包中的 .NET core 中缺少 JObject

c# - Column Extent1.Id 在带有 Entity Framework 6 和 PostgreSQL 的 Mono 中不存在