Filomena
Filomena

Reputation: 11

POST 500 Internal Server Error

I'm going mad with this error.

POST http://localhost:56105/Home/getContactbyId?ConId=%225%22 500 (Internal Server Error)

Hope you'll be able to help me. I need to get Contact data based on ContactId. Following is the relevant code (apologies if I missed something, I'll add if needed):

contactController.js

ContactsApp.controller("contactController", function ($scope, $rootScope, $routeParams, $location, myService) {
     function getContactById(id) {
         var getting = myService.get_Contact_By_Id(id);    
         getting.then(function successCallback(response) {
             $rootScope.Name = response.data.Name;
         }, function errorCallback(response) {
             return "Error";
         });
     }
    function init() {
        var contactId = $location.path().split("/")[2];
        console.log(contactId); //this loggs the correct Id
        getContactById(contactId);
    }
    init();
}

myService.js

ContactsApp.service("myService", function ($http) { 
    this.get_Contact_By_Id = function (ConId) {
    console.log(ConId);  //this logs the correct id
    return $http({
        method: 'post',
        url: '/Home/getContactById',
        params: {
            ConId: JSON.stringify(ConId)
        }
    });
  }
}

HomeController.cs

public class HomeController : Controller
{
     public string getContactById(int ConId)
     { 
         int id_int = Convert.ToInt32(ConId);
         using (ContactsDBEntities contactsData = new ContactsDBEntities())
         {
             var theOne = contactsData.Contacts.Where(x => x.Id == id_int).FirstOrDefault();
             return theOne.Name;
         }
     }
}

Upvotes: 1

Views: 1076

Answers (1)

F.Igor
F.Igor

Reputation: 4360

Using JSON.stringify(ConId) returns a quoted string with the ConId number. params expects a simple object with name : value pairs. Simply use

params: {
            ConId: ConId
        }

When the ConId is sent using stringify(), the Convert.ToInt32(ConId) call will throw an Exception for conversion (expected NUMBER, not 'NUMBER'). You should put some validation after using that conversion, or a try - catch block.

Also it could be a problem with returning FirstOrDefault() if no result is found. You should check also the theOne variable before using it.

You should check the server application log (Application Event Viewer) to see the exception causing the HTTP Error 500.

Upvotes: 3

Related Questions