如果 angular 中有多个 Post 方法,则调用网络 Api 方法 2

Call web Api method if there are more then one Post method from angular 2

我有一个网站 api,其中有 2 个 Post 方法。

我从 angular 2 调用该方法,但每次它都调用第一个方法 (PostEmployee)。我在第二种方法中使用了路由。

  public IHttpActionResult PostEmployee(Employee employee)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Employees.Add(employee);        

        return CreatedAtRoute("DefaultApi", new { id = employee.EmpID }, employee);
    }

    [Route("Login")]     
    public IHttpActionResult Login(string username, string password)
    {
        Employee emp = db.Employees.FirstOrDefault(t=>t.EmpName == username && t.Address == password);          


        return CreatedAtRoute("DefaultApi", new { id = emp.EmpID }, emp);
    }

Angular2服务代码:

login(username: string, password: string) {
    debugger
    let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post('http://localhost:49221/api/Employee/Login', { username: username, password: password }, headers)
        .map((response: Response) => {                
            let user = response.json();
            if (user && user.token) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
            }
        });
}


create(employee: Employee) {
    let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
    let options = new RequestOptions({ headers: headers });
   // let body = JSON.stringify(employee);
    return this.http.post('http://localhost:49221/api/Employee', employee, headers).map((res: Response) => res.json());
}

登录和创建服务调用的方法PostWeb的员工api.

如何从服务中调用webapi的登录方法?

谢谢

我确信您的 "WebApiConfig" 文件配置不正确。

这个答案应该对你有帮助:

Link 1

Link 2