Ali
Ali

Reputation: 927

Web Api and AngularJs

Straightly diving into the problem:

There is angularJs controller in which it calls a function defined inside a factory. The factory function calls an Api POST action which accepts a '[FromBody]string' parameter. The problem is raised exactly here. Actually, the parameter is always null! while inside the factory method it has the desired value. Here is a bit of code:

The angularJs controller:

$scope.readText = function() {

        var element = document.getElementsByClassName('news-content');

        if (element[0] != undefined) {
            elementPureText = element[0].innerText;
        }

        dataFactory.createTextFile(elementPureText)
            .succes(function(data, status, headers, config) {

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

            });
    };

The factory code:

philadelphiaApp.factory('dataFactory', ['$http', function ($httpt) {

var dataFactory = {};

dataFactory.createTextFile = function (text) {
    return $httpt.post('api/textmanager/textWriter', { '': text });
};

return dataFactory;

}]);

And finally the ApiController:

[HttpPost]
    [ActionName("TextWriter")]
    public HttpResponseMessage PostTextWriter([FromBody]string text)
    {
        if (String.IsNullOrEmpty(text) || text.Length == 0)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
        }

        if (!Directory.Exists(FileDirectory))
        {
            try
            {
                Directory.CreateDirectory(FileDirectory);
            }
            catch (Exception)
            {

                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }

        try
        {
            File.WriteAllText(FileDirectory, text);
        }
        catch (Exception)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
        }

        return Request.CreateResponse(HttpStatusCode.OK, text);
    }

After visiting and searching over the web I came across with a lot of forums and websites which provide solutions but I could not handle it yet. I assume the best out of which is the following URL:

http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

I highly appreciate any help on this...

Upvotes: 1

Views: 1226

Answers (3)

Ali
Ali

Reputation: 927

Actually I found the answer after days of toils... and it seems easy; simply adding the Content-Type: application/json in web api client side call and well done! But appreciate those who provided solutions.

Upvotes: 0

Josh
Josh

Reputation: 44916

The issue has to do with how the data is being encoded, and how WebAPI is trying to deserialize that on the back end.

By default $http will pass all POST requests with content-type:application/json and it attempts to try and encode your data that way. You could attempt to set the content-type to something like text/plain but then you need a custom media formatter for WebAPI to be able to handle that.

Your path of least resistance here is to create a simple request object like this:

public class TextWriterRequest
{
    public String Text { get; set; }
}

And then modify your method to accept that object as the input. No need to use [FromBody] since WebAPI will look for complex objects in the body by default.

public HttpResponseMessage PostTextWriter(TextWriterRequest text)

Then you can make sure your data being passed matches the request object via the $http service:

$http({
    method: 'POST',
    url: '/api/textmanager',
    data: { text: text }
});

This will deserialize correctly on the service, and life will be good once again.

Upvotes: 1

Zerot
Zerot

Reputation: 196

You are sending over an object with a field named ''(empty string) and the value of your text. However, your webapi backend expects a string, not an object. It can't deserialize the object into the string, so it will be null.

You need to send the string directly and not stuff it in an object. Like this:

return $httpt.post('api/textmanager/textWriter', text);

Upvotes: 0

Related Questions