1

I'm doing my first angularsjs-asp.net web api project. I am trying to send a $scope.user object to asp.net web api as follows-

AngularJS controller code-

    $scope.user = {};
    $scope.navbarCollapsed = true;
    $scope.save = function () {
          $http.get('/api/Login', $scope.user).
             success(function (data, status, headers, config) {
                 $window.location.href = 'app/views/dashboard.html';

             }).
             error(function (data, status, headers, config) {
             alert(status);    
      });      
}

ASP.NET web API code:

public class LoginController : ApiController
{
    public HttpResponseMessage get( LoginUser user) //user is shown null
    {

    }
}

user is shown null in server side. Any help?

UPDATE----------------

public class LoginUser
{
    public String LoginName { get; set; }

    public String LoginPassword { get; set; }
}
3
  • What fields $scope.user has? What fields LoginUser has ? Commented Nov 3, 2014 at 10:07
  • if your trying to send a object to server best thing is to do is the POST method. Commented Nov 3, 2014 at 10:08
  • Fast fix (not the best solution): encode to json your $scope.user JSON.parse($scope.user); In code behind use public HttpResponseMessage get( String user) {LoginUser decodeuser = JsonConvert.DeserializeObject<LoginUser>(user)} Commented Nov 3, 2014 at 10:09

1 Answer 1

3

As complex data to WebApi is normally send in the request body, you have to specify that the information is encoded in the url:

public HttpResponseMessage get([FromUri]LoginUser user)
{

}

and send the user as follows:

$http.get('/api/Login',
    {
        'params': $scope.user
    });

But as your are sending login information I would recommend to switch to another HTTP verb like POST

UPDATE

Here is an example for the POST verb:

public HttpResponseMessage post(LoginUser user)
{

}
$http.post('/api/Login', $scope.user);
Sign up to request clarification or add additional context in comments.

1 Comment

Now it's working. Great. As you suggested, would you please post an example with POST verb? I am very new to web api world. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.