Search code examples
c#angularjshttphttp-status-code-404azure-web-app-service

Why does changing controller's parameter provoke http Post 404 error?


I am developing an Azure Web app with a database. I've a model and controller for the database. I'm trying to Post data on the database, but have some trouble understanding why does this code send a 404 error when sending data from the Web-Client to the controller.

Here is how I send the data in AngularJS (parameter is a Json string):

$http({
        method: 'post',
        url: serviceBasePath + "/api/suscribe",
        data: parameter,
        headers: { 'Content-Type': 'application/json' }
    }).then(function (response) {
        userService.SetCurrentUser(response.data);
        defer.resolve(response.data);
    }, function (error) {
        defer.reject(error.data);
    })

On the controller side, I get 404 if the controller is :

[HttpPost]
[Route("api/suscribe")]
public IHttpActionResult PostGTW_Utilisateur(String JsonString)
{
    //
}

But if I leave the model as a parameter, the 404 error is gone :

[HttpPost]
[Route("api/suscribe")]
public IHttpActionResult PostGTW_Utilisateur(User u) 
{
    //
}

error 404 on post request with Json data Json object class :

public class JsonSuscribeModel
{
    public Utilisateur user { get; set; }
    public string guid { get; set; }
    public string password2 { get; set; }
}

Solution

  • You miss the endpoint since it does not know what JsonString is. You sent a JSON but in the controller model, you told it to listen for string. Open up Chrome (or other) dev tools and see EXACTLY what you are sending with the request.

    Here is another tip:

    $http({
            method: 'post',
            url: serviceBasePath + "/api/suscribe",
            data: parameter,
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            userService.SetCurrentUser(response.data);
            defer.resolve(response.data);
        }, function (error) {
            defer.reject(error.data);
        })
    

    I have seen the misuse of promises SO many times. Why would you use $http (which is itself a promise) and then process it in service and return ANOTHER promise? You can simply return $http (and resolve its promises in a controller. You are gonna have to resolve this new promises you are returning anyway, so why have an extra step.

     return $http({
                method: 'post',
                url: serviceBasePath + "/api/suscribe",
                data: parameter,
                headers: { 'Content-Type': 'application/json' }
            }).then(function (response) {
                userService.SetCurrentUser(response.data);
                return response.data;
            }, function (error) {
                return error.data;
            })
    

    This way you return entire $http and you instruct it what to return in success and error. Since itself it's a promise it will behave same as before.