Search code examples
angularasp.net-web-apiasp.net-web-api-routing

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


I have a web api which have 2 Post method.

I call that method from angular 2 but every time it calls first method (PostEmployee). I have used route on my second method.

  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 service code:

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

Both login and create method of service call PostEmployee of Web api.

how to call login method of web api from service?

Thanks


Solution

  • I am confident that your "WebApiConfig" file is not configured correctly.

    This answers should help to you:

    Link 1

    Link 2