以下路线代码:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
以下控制器代码:
// POST api/values
[HttpPost]
public void Post([FromBody]Employee employee)
{
employeeManager.CreateAsync(employee);
}
除post方法之外的所有其他方法。
从角度组件调用:
onSubmit(employeeItems: any) {
console.log(employeeItems);
this.getData();
var headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
this.http.post('api/Employee/Post', employeeItems, { headers: headers }).subscribe();
this.createEmployeeFlag = false;
}
我甚至从邮递员那里尝试过,但没有运气。
答案 0 :(得分:2)
您的网址和路由模板不匹配
[Route("api/[controller]")]
public class EmployeeController : Controller {
[HttpPost]
public async Task<IActionResult> Post([FromBody]Employee employee) {
await employeeManager.CreateAsync(employee);
return Ok();
}
}
并更新您的主叫网址以调用默认端点api/Employee
onSubmit(employeeItems: any) {
console.log(employeeItems);
this.getData();
var headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
this.http.post('api/Employee', employeeItems, { headers: headers }).subscribe();
this.createEmployeeFlag = false;
}
答案 1 :(得分:1)
这是您在服务中需要的代码,这里有两个问题,首先是URL,它需要是完整的URL路径。第二个是您在将其映射到Observable
onSubmit(employeeItems: any) {
let url: string = 'http://localhost/api/employee'; //this will be the complete url that you would hit with say postman
this.getData(); //I'm not sure what this is so I'm leaving it here
this.http.post(url, employeeItems)
.map((response: Response) => response.json())
.Subscribe((response: any) => {
//do whatever with the response here.
});
this.createEmployeeFlag = false;
}
我建议将其分解为*.service.ts
文件。
*.service.ts
public postEmployee(employeeItems: any): Observable<any> {
let url: string = 'http://localhost/api/employee'; //this will be the complete url that you would hit with say postman
this.http.post(url, employeeItems)
.map((response: Response) => response.json());
}
在*.component.ts
构造函数(私有服务:服务){}
onSubmit(employeeItems: any) {
this.getData(); //I'm not sure what this is so I'm leaving it here
this.service.postEmployee(employeeItems)
.Subscribe((response: any) => {
//do whatever with the response here.
});
this.createEmployeeFlag = false;
}