Michael
Michael

Reputation: 13636

Why I get null when I make post JSON to web API method?

I create and send JSON from cilent to web api method.But I get NULL in end point function.

I have this function:

function genarateDirectives(workPlanServise) {
    var dataObj = {
        name: 'name',
        employees: 'employee',
        headoffice: 'master'
    };

    return workPlanServise.generateFilter(dataObj)
        .then(function (result) {
            return result.data;
        });
}

Here is service I use:

(function () {
    "use strict";

    angular.module("workPlan").factory("workPlanServise", ["$http", "config", workPlanServise]);

    function workPlanServise($http, config) {
        var serviceUrl = config.baseUrl + "api/workPlan/";
        var service = {
            getAll: getAll,
            getSubGridContent: getSubGridContent,
            generateFilter:generateFilter
        };
        return service;

        function getAll() {
            return $http.get(serviceUrl);
        }

        function getSubGridContent(clientId) {
            return $http.get(serviceUrl + '?clientId=' + clientId);
        }

        function generateFilter(objData) {
            return $http.post(serviceUrl, objData );
        }
    }
})();

Here end point web api function:

    [HttpPost]
    public async Task<IHttpActionResult> Post([FromBody]string objData) 
    {
        try
        {
            return null;
        }
        catch (Exception)
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
        }
    }

Any idea why objData is always null?

Upvotes: 0

Views: 752

Answers (2)

Elger Mensonides
Elger Mensonides

Reputation: 7029

Create a model class with fields that match the fields in objData in your web api.

The web api model binder will fill it for you. Don't forget to check if the request has contentType: "application/json" in the headers. (A standard $http call will have that)

For example:

public class SomeModel
{
    public string Name { get; set; }

    public int Number { get; set; }

    public string Description { get; set; }
}

And then post it to:

[HttpPost]
public async Task<IHttpActionResult> Post(SomeModel objData) 
{ ....

OR

If you really need to post a string to Web api, you would need to pass text/plain in the header of your request instead of application/json and add an additional text/plain formatter to your web api. See here for more info

Upvotes: 1

Because you are binding an JSON object to a string, which is not valid. Create model

public class MyModel
{
    public string Name { get; set; }

    public string Employees { get; set; }

    public string HeadOffice { get; set; }
}

And use it in the action without the [FromBody] attribute since by default all reference types are bound from the body.

public async Task<IHttpActionResult> Post(MyModel objData) 
{
    // work with objData here
}

Upvotes: 2

Related Questions