在Asp.net core Web API控制器中,使用Post方法返回404错误

4
路由代码如下:
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方法之外,所有其他方法都可以正常工作。

从Angular组件调用:

 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;
    }

我甚至尝试了Postman,但没有成功。

1
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing - Jota.Toledo
2个回答

4
您的URL和路由模板不匹配。
[Route("api/[controller]")]
public class EmployeeController : Controller {

    [HttpPost]
    public async Task<IActionResult> Post([FromBody]Employee employee) {
        await employeeManager.CreateAsync(employee);
        return Ok();
    }
}

并将您的调用URL更新为调用默认端点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;
}

谢谢你的帮助,"并更新您的调用URL以调用默认端点api/Employee" 这正是我的问题所在!干杯 - Samra

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文件中:

构造函数:constructor(private service: Service) {}

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接