[英]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.