[英]Adding new record to DB through REST API using Angularjs
I'm trying to add a new record to the database using REST API.我正在尝试使用 REST API 向数据库添加新记录。 The DELETE and GET methods work just fine, but I can't figure out what's wrong with the POST method. DELETE 和 GET 方法工作得很好,但我无法弄清楚 POST 方法有什么问题。
My API Controller:我的 API 控制器:
[HttpPost] // POST: api/Contacts //to add image as param?
public void InsertNewContact([FromBody]Contact Contact)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConStr"].ConnectionString);
SqlCommand cmd = new SqlCommand(@"INSERT INTO Contacts(Name,Phone,Mail,City,Address) VALUES(@Name, @Phone,@Mail,@City,@Address)", con);
SqlParameter Name = new SqlParameter("@Name", Contact.Name);
cmd.Parameters.Add(Name);
SqlParameter Phone = new SqlParameter("@Phone", Contact.Phone);
cmd.Parameters.Add(Phone);
SqlParameter Mail = new SqlParameter("@Mail", Contact.Mail);
cmd.Parameters.Add(Mail);
SqlParameter City = new SqlParameter("@City", Contact.City);
cmd.Parameters.Add(City);
SqlParameter Address = new SqlParameter("@Address", Contact.Address);
cmd.Parameters.Add(Address);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
}
finally
{
con.Close();
}
}
HTTP POST request in HTML: HTML 格式的 HTTP POST 请求:
$scope.add_to_db = function ()
{
//insert contact to db
$http.post(url + "/api/Contacts",
JSON.stringify({ Name: $scope.contactName, Phone: $scope.contactPhone, Mail: $scope.contactMail, City: $scope.contactCity, Address: $scope.contactAddress}))
.then(function (res) {
$state.go("contacts");
}, function (err) { alert(err); });
}
The response is returned to the success function but nothing's changed in the database.响应返回到成功函数,但数据库中没有任何更改。 What could be the problem here?这里可能有什么问题?
Catch Block is Empty to know the error, Usually i go through these scenarios and i make sure the following are implemented in the code to track down the failure reason: Catch Block is Empty 以了解错误,通常我会经历这些场景,并确保在代码中实现以下内容以追踪失败原因:
1) @RequestBody in API controller should be accepting Contact model data. 1) API 控制器中的@RequestBody 应该接受Contact模型数据。
2) Check if JSON object created at angular is in sync with Contact model/ POJO. 2) 检查以 angular 创建的 JSON 对象是否与Contact模型/POJO 同步。
3) Use POSTMAN to debug only REST API initially, which can help you to track down failure. 3) 最初使用POSTMAN仅调试 REST API,这可以帮助您跟踪故障。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.