skary
skary

Reputation: 69

Post Data to WebApi from AngularJS

i want to Post a User to WebApi

Ive written this Controller :

 public class AccountController : ApiController
{
    public UserModel Get([FromUri]string username, [FromUri]string password)
    {
        var repository = new MongoRepository<User>();
        User result = repository.Single(x => x.Username == username && x.Password == password);
        UserModel user = result.ToUserModel();
        if (result != null)
        {
            result.LastLogin = DateTime.Now;
            user.LastLogin = DateTime.Now;
            repository.Update(result);
        }

        return user;
    }

    public GenericResultModel Post(User user)
    {
        var repository = new MongoRepository<User>();
        var existingUser = repository.Single(x => x.Username == user.Username || x.EmailAdress == user.EmailAdress);
        if (existingUser == null)
        {
            if (repository.Add(user) != null)
            {
                return new GenericResultModel{Success = true, Errors = new List<string>()};
            }
            return new GenericResultModel(){Success = false, Errors = new List<string>(){"There was an Error adding the User !"}};
        }
        return new GenericResultModel(){Errors = new List<string>(){"The User already exists !"}, Success = false};
    }
}

My RouteConfig:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

And my AngularJS Controller

mod.controller('accountCtrl', function ($scope, $http, $window, $location) {

$scope.credentials = { username: '', password: '' };
$scope.Login = function () {
    $http({
        method: 'GET',
        url: 'http://localhost:9239/Api/Account/Get?username=' + $scope.credentials.username + '&password=' + $scope.credentials.password,
        /* data: JSON.stringify(credentials), */
        headers: { 'Content-Type': 'application/json; charset=utf-8', 'dataType': 'json' }
    }).
        success(function (data, status, headers, config) {
            $window.sessionStorage.setItem('loginToken', data.Id);
            //$location.redirectTo('/Home');
        }).
        error(function (data, status) {
            console.log("Request Failed");
        });
};

$scope.registerModel = { username: '', password: '', passwordrepeat: '', email: '', emailrepeat: '' };
$scope.RegisterUser = function () {
    $http.post('http://localhost:9239/Account/',$scope.registerModel);
};

});

When i login, everythign works fine. But when i post a new User i get a 404 Not Found Error.

I tryied the [FromBody] Attribute but it didnt worked

When i debug my Code wont hit by the Service ...

Any Ideas ?

Upvotes: 1

Views: 1752

Answers (1)

Tim
Tim

Reputation: 43314

Assuming you didn't make any typos in the api url you POST to, the problem is not in your angular code.


HTTP 404 Not Found

The 404 or Not Found error message is a HTTP standard response code indicating that the client was able to communicate with the server, but the server could not find what was requested.


If you had tried to POST a user to http://localhost:9239/Account using, for example, the program curl, you would also have gotten this 404 code.

If you had opened your browser and surfed to http://localhost:9239/Account you would also have gotten this 404 code.

Basically what it means is that the url you are trying to POST to doesn't 'exist'. I've been in this situation myself because I simply typo'd the url. The only other explanation I can think of is that the server is running fine, but there is no implementation for /Account, e.g. calls to that url aren't handled.

Upvotes: 2

Related Questions