【问题标题】:Call web Api method if there are more then one Post method from angular 2如果 Angular 2 有多个 Post 方法,则调用 web Api 方法
【发布时间】:2017-03-15 09:58:50
【问题描述】:

我有一个有 2 个 Post 方法的 web api。

我从 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的登录方法?

谢谢

【问题讨论】:

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


    【解决方案1】:

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

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

    Link 1

    Link 2

    【讨论】:

    • 谢谢@riwex。
    猜你喜欢
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2015-10-08
    • 2014-07-10
    相关资源
    最近更新 更多