Web api Post方法没有从角度2中击中

时间:2018-02-20 08:38:39

标签: c# asp.net-web-api angular2-routing

我的web api方法没有从angular 2中命中,即使在控制台中没有错误,但是当我使用Jquery ajax调用检查时,同样正常工作。

API方法---

// POST api/values
public void Post([FromBody]Customer objCustomer)
{
    System.Xml.Serialization.XmlSerializer writer =
    new System.Xml.Serialization.XmlSerializer(typeof(Customer));

    var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//SerializationOverview.xml";
    System.IO.FileStream file = System.IO.File.Create(path);

    writer.Serialize(file, objCustomer);
    file.Close();
    return;
}

angular 2 call ---不工作

saveCustomer(): Observable<Customer[]>{
    var body = {"userName": "sonoo", "Age": "56000"}

     this.headers.append('Content-Type', 'application/json');
     var options = new RequestOptions({method:RequestMethod.Post, headers: this.headers});

     return  this.http.post("http://localhost:57899/api/values", body,options)
            .map(res => res.json().subscribe(
    (data) => console.log(data)));              
}

注意:Get方法工作正常。 感谢

1 个答案:

答案 0 :(得分:0)

看起来问题出在你的ts代码中。试试这个:

saveCustomer(): Observable<Customer[]>{
  const body = { userName: 'sonoo', Age: '56000'};    
  const headers = new HttpHeaders({ 'Content-Type': 'application/json' });    
  return this.http.post<Customer>('http://localhost:57899/api/values', body, { headers });
}

您还需要从API中返回Customer对象,如下所示:

return this.CreatedAtRoute("DefaultApi", new { id = customer.id}, customer);