2017-07-25 43 views
1

路由代码Asp.net核心Web API控制器返回404:Post方法在下面

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

甚至从邮差我试过,但没有运气。

+1

https://docs.microsoft.com/en-us/aspnet/核心/ mvc /控制器/路由 –

回答

1

您的网址和路由模板不匹配

[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; 
} 
+0

感谢它的工作! –

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