我对这个错误很生气。
POST
http://localhost:56105/Home/getContactbyId?ConId=%225%22 500 (Internal Server Error)
希望你能够帮助我。我需要根据ContactId获取联系人数据。以下是相关代码(如果我错过了某些内容,请道歉,如果需要,我会添加):
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;
}
}
}
答案 0 :(得分:3)
使用JSON.stringify(ConId)
会返回带有ConId
数字的带引号的字符串。 params
期望一个具有name : value
对的简单对象。只需使用
params: {
ConId: ConId
}
使用ConId
发送stringify()
时,Convert.ToInt32(ConId)
调用将引发转换异常(预期NUMBER,而不是'NUMBER')。您应该在使用该转换或try-catch块后进行一些验证。
如果没有找到结果,返回FirstOrDefault()
也可能是个问题。在使用之前,您还应该检查theOne
变量。
您应该检查服务器应用程序日志(Application Event Viewer)以查看导致HTTP Error 500的异常。