[英]Angular 4 Http Post not hitting API Post Method in DotNet Core 2.0 API Controller
[英]Web api Post method is not hitting from angular 2
我的Web api方法沒有遇到問題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;
}
角度2通話--不起作用
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方法工作正常。 謝謝
看來問題出在您的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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.