Error with Asp.NET Web.API + Angularjs

Asked

Viewed 752 times

5

I have my method C# thus

[ResponseType(typeof(Categoria))]
public async Task<IHttpActionResult> Post(Categoria model) {
    if (!ModelState.IsValid) {
        return BadRequest(ModelState);
    }
    if (_repositorio.InsertOrUpdate(model, out Res)) {
        _repositorio.Save();
        return CreatedAtRoute("DefaultApi", new { id = model.Id }, model);
    }
    return BadRequest("Erro ao tentar salvar, tente novamente mais tarde");    
}

I have my factory thus:

.factory("categoriasService", function($http, config, $q) {
    var _postItem = function(record) {
        var deferred = $q.defer();
        $http.post(config.baseUrl + "/api/Categoria/Post", record).then(
            function(result) {
                deferred.resolve(result.data);
            },
            function (erroResult) {
                deferred.reject();
            }
        );
        return deferred.promise;
    };
    return {            
        postItem: _postItem
    };
})

By calling in my controller:

.controller("newCategoriaCtrl", [
    "$scope", "$http", "$window", "categoriasService", "modalConfirmationService", "$routeParams",
    function ($scope, $http, $window, categoriasService, modalConfirmationService, $routeParams) {            
        if ($routeParams.id !== undefined) {
            categoriasService.find($routeParams.id).then(function (result) {
                $scope.newCategoria = result;
            });
            $scope.titleAcao = "Alterar";
        } else {
            $scope.newCategoria = { Id: 0 };
            $scope.titleAcao = "Cadastrar";
        }

        $scope.save = function() {
            //console.log($scope.newCategoria);
            categoriasService.postItem($scope.newCategoria)
            .then(function (newCategoria) {
                console.log(newCategoria);//aqui o objeto está sempre vazio por que acontece o erro 500.
                modalConfirmationService.getModalInstance("Sucesso", "Dados salvos com sucesso!");
            },
            function() {
                modalConfirmationService.getModalInstance("Erro", "Não foi possível executar sua ação, tente novamente mais tarde.");
            })
            .then(function() {
                $window.location = "#";
            });
        };
    }
]);

When I call the application, without enabling the debug in the browser console, always occurs error 500 and does not save the information in the database.

http://localhost:54100/api/Categoria/Post 500 (Internal Server Error)

But if I activate debug mode in VS, it gives the same error in the console, but the information is saved in the database.

What’s wrong? I have to set up something in the web app.api?

  • In order to avoid any errors in DEBUG mode, your exceptions may be disabled. try enabling NO VS, DEBUG -> WINDOWS -> EXCEPTION SETTINGS and Enable C++ Exceptions, Common Langugages Runtimeexceptions and GPU Memomy Access Exception

1 answer

0

Only with the above information it is difficult to help, however error 500 happens, why you do not have a specific treatment p/ return the error to screen, ie. in the DEBUG version of VS. your controller (webApi) is being called. but probably at the time of executing this line of code

return CreatedAtRoute("DefaultApi", new { id = model.Id }, model); must be popping an error, so the error that returns to the client is 500 As soon as there is no treatment, what I use is an error handling

Try{}catch(){}. where I return an object from HttpResponseMessage with the status treated by me, and an Exception p/ receive on the client and perform the treatments.

  • No.. when debugging using VS, there is no error. The interesting thing is that it only works the first call, then it stops working. when calling the direct link.

  • It will not really pop an error in VS, it returns this 'error', in Replay with status 500 you understand ? if you put a Try catch in your method will probably catch what is happening.

  • OK, I’ll test with Try and give you a feedback. For now thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.