C# – Angularjs and ASP.NET Web Api cause 500 Internal Server Error on $http.post

angularjsasp.netasp.net-web-apic++

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.

Best Solution

If what you're saying is true and the code execution never reaches your PostProduct() action method in your ProductsController, then the problem must be either earlier in the Web API pipeline (e.g. any global message handlers, filters, etc.) or with the client.

It's easy to eliminate the client code from the process by firing the same request and data to your Web API using Fiddler, Postman, etc. I know it's a basic thing to suggest, but since you didn't clarify if you tried this step or not in your question, I had to mention it.

If the request works correctly when sent like that, then it's a problem with your client code. Otherwise, you need to take a look at the code that's executed on your server before your request gets routed to your controller.