如果角度2中有多个Post方法,则调用web Api方法

时间:2017-03-15 09:58:50

标签: angular asp.net-web-api asp.net-web-api-routing

我有一个web 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);
    }

Angular 2服务代码:

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

登录和创建服务方法都调用了Web api的PostEmployee。

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

由于

1 个答案:

答案 0 :(得分:1)

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

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

Link 1

Link 2