POSTing from Angular to .net WebAPI

前端 未结 2 1715
你的背包
你的背包 2020-12-05 14:04

I\'m using an Angular $resource to post a model to a webapi endpoint, but Angular sends the data in the request payload, rather than a JSON body or form parameters. As a res

相关标签:
2条回答
  • 2020-12-05 14:35

    For me this just worked fine. Below is the server-side code

        [HttpPost]
        public void Disconnect([FromBody] Models.Users.User model) { ... }
    

    and the requesting client code will be,

    var dataToPost ={ id : 3, firstName : 'Test', lastName : 'User', username : 'testuser', isApproved : true, isOnlineNow : true, isChecked: true };
    
                var config = {
                    headers : {
                        'Content-Type': 'application/json;charset=utf-8;'
                    }
                }
                $http.post(thisIsUrl, dataToPost, config).then(......
    
    0 讨论(0)
  • 2020-12-05 14:57

    You could use the $http module.

    Here's an example:

    <!DOCTYPE html>
    
    <html ng-app>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
    </head>
    <body>
        <div ng-controller="TestController">
            <ul ng-model="person">
                <li>FirstName: {{person.FirstName}}</li>
                <li>LastName: {{person.LastName}}</li>
                <li>UserName: {{person.Username}}</li>
                <li>IsApproved: {{person.IsApproved}}</li>
                <li>IsOnlineNow: {{person.IsOnlineNow}}</li>
                <li>IsChecked: {{person.IsChecked}}</li>
            </ul>
        </div>
    
        <script type="text/javascript" src="~/scripts/angular.min.js"></script>
        <script type="text/javascript">
            function TestController($scope, $http) {
                var data = { "Id": 3, "FirstName": "Test", "LastName": "User", "Username": "testuser", "IsApproved": true, "IsOnlineNow": true, "IsChecked": true };
                $http.post(
                    '/api/values',
                    JSON.stringify(data),
                    {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }
                ).success(function (data) {
                    $scope.person = data;
                });
            }
        </script>
    </body>
    </html>
    

    Assuming the following controller:

    public class ValuesController : ApiController
    {
        [HttpPost]
        public User Post(User model)
        {
            return model;
        }
    }
    
    0 讨论(0)
提交回复
热议问题