Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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...

share|improve this question

3 Answers 3

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);
share|improve this answer
    
thanks I did it previously but still the NULL value. Actually, I sent the object as it was suggested on the mentioned URL (inside my question) –  Ali Ashoori Jun 12 at 20:00

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.

share|improve this answer
    
Well.. what you suggested seems like a reasonable solution but I am sorry to say that no it doesn't work on my code... as am working on a sample app and coming up completely out of idea.. I would create a new solution from the scratch and perhaps I could figure it out! –  Ali Ashoori Jun 12 at 20:42
    
@AliAshoori - This seems quite strange to me. Mainly because I actually created a solution before answering this just to ensure it worked as expected. –  Josh Jun 12 at 20:58
up vote 0 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.