I am using Angularjs and ASP.NET Web Api, my $http.get, $http.put and $http.delete work just fine, but when I call $http.post I get 500 Internal Server Error, here is my code:
My Angularjs Controller insert function:
$scope.insert = function () {
var data = '{ "Id": "1", "Name": "test", "Category": "r", "Price": "456.00" }';
$http.post('api/products', data).success(function (data) {
alert("it works");
}).error(function () {
console.log(Error);
alert('Error reading JSON file. - ' + data);
});
}
My model in C#:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
My controller in C#:
public class ProductsController : ApiController
{
public void PostProduct(Product product)
{
if (product == null)
{
throw new ArgumentNullException("product is NULL");
}
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("INSERT INTO [AdventureWorks2012].[Production].[Product2] ( [Name], [ListPrice], [ProductLine]) VALUES ('" + product.Name + "', '" + product.Price + "', '" + product.Category + "')", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Code never reaches brake points in C# controller and throws 500 Internal Server Error.
Please advise.