Http Angularjs通过Web API导致内部服务器错误

问题描述 投票:0回答:1

我通过web API从angularjs进行了一个简单的http post插入操作。但是我不知道为什么我不断收到内部服务器错误。 http GET函数运行正常。但是对于http帖子,数据已通过WebAPI成功插入到数据库中,但是未收到来自服务的响应。正在获取内部服务器错误500。

WebAPI

 // POST: api/Website/InsertEmployee
[ResponseType(typeof(Employee))]
[HttpPost]
public IHttpActionResult InsertEmployee(Employee employee)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    objCSADBEntities.Employee.Add(employee);
    objCSADBEntities.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
}

Angularjs服务

(function () {

    var app = angular.module('myApp');

    app.factory('websiteService', ['$http', function ($http) {
        var factory = [];

        factory.insertEmployee = function (webAPIHostName,employee) {
            var request = $http({
                method: 'POST',
                url: webAPIHostName + '/Website/InsertEmployee',
                data: employee
            })
            return request;
        }

        return factory;
    }
   ]);
})();

Angularjs控制器(在那里调用服务,我收到内部服务器错误500)

var employee = {
    EmployeeID: 1,
    Name: 'Test',
    Phone: '111-111-1111'
};

var insertEmployee = websiteService.insertEmployee($scope.webAPIHostName , employee);
insertEmployee.then(function (response) {
    alert("Submitted Employee Successfully.");
    //success response here
}, function (error) {
    // error handling here
});
angularjs asp.net-web-api http-post
1个回答
0
投票

您能否使用提琴手或邮递员验证您的API调用是否返回了您期望的结果?一旦可以确认WebAPI返回的是有效的HttpStatus(200到<400),就可以检查前端代码(angularjs)。调用webAPIHostName +'/ Website / InsertEmployee'并将JSON正文(假设其JSON)添加到您的提琴手调用中。将方法更改为POST,并包含在标题中

内容类型:application / json

如果响应不理想,请尝试从以下位置更改API返回值:>

return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);

return Request.CreateResponse(HttpStatusCode.OK, employee);

如果可以验证POST是否按预期工作,请检查angularjs。

对于Angularjs,您的http调用可以更新为

angular.module('myApp').factory('websiteService', ['$http', function ($http) {            
    var insertEmployee;

    insertEmployee = function (webAPIHostName, employee) {            
        return $http.post(webAPIHostName + '/Website/InsertEmployee', JSON.stringify(employee));
    }

    return {
        insertEmployee: insertEmployee
    };
}]);



// Angular Controller

var employee = {
    EmployeeID: 1,
    Name: 'Test',
    Phone: '111-111-1111'
};

websiteService.insertEmployee($scope.webAPIHostName , employee)
    .then(function (response) {
        alert("Submitted Employee Successfully.");
        //success response here
      }, function (error) {
        // error handling here
    });
© www.soinside.com 2019 - 2024. All rights reserved.