What is required for a web API to bind models?

Using angular I am sending an HTTP request

$scope.addFiles = function (files) {
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            $http.post('/api/files/addFiles', JSON.stringify({ testName: "test", someRandomCrap:"asdf"}));
        }
    }

      

I am getting the request correctly in my controller. However, the answer is null: Null Request :(

After verifying that the content header is in order and that the information has indeed been sent, I replaced the sample object with a generic object:

It Works!

Here and there. It works! From this, I guess the web API cannot bind to my object. This brings me to my question: what web API needs to be associated with an object?

TestObject:

public class TestObject
{
    string testName { get; set; }
    string someRandomCrap { get; set; }
}

      

+3


source to share


2 answers


Try the following:

$scope.addFiles = function (files) {
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        $http.post('/api/files/addFiles', { testName: "test", someRandomCrap:"asdf"});
    }
}

      

Two things:



  • In the asp.net api, the entire request object is bound to a parameter, so we don't need to specify the property name in the request body. Look at this: web api put recognizes query strings but not body
  • Not necessary JSON.stringify

    , otherwise it will treat your entire object as a string. In the second figure it fileName

    has a line like

Also try making your objects public:

public class TestObject
{
    public string testName { get; set; }
    public string someRandomCrap { get; set; }
}

      

+2


source


You just need the object itself:



$scope.addFiles = function (files) {
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        $http.post('/api/files/addFiles',{ fileName: { testName: "test", someRandomCrap:"asdf"}});
    }
}

      

0


source







All Articles