2

I am using AngularJS and I am trying to send in a json from my service to the webAPI controller. When I send via I recieve null in the parameter in webApi function.

My function service is:

angular.module('productsApp')
    .service('ProductDetailService', ['$http', function ($http) {
        var urlBase = "/api/productdetail";

        this.Salvar = function (product) {
            var mydata = JSON.stringify(product);
            debugger;

            return $http({
                method: 'POST',
                url: urlBase + "/salvar/" + mydata,
                data: mydata,
                headers: { 'Content-Type': 'application/json' }
            });
        };
    }]);

my code in the webAPI is:

public class ProductDetailController : BaseController
{
    [Route("api/productdetail/salvar/{item}")]
    [HttpPost]
    public bool Salvar(string item)
    {
        return true;
    }
}

my app.js is:

var app = angular.module('productsApp', ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider)
{
    $routeProvider.when('/', {
        controller: 'ProductController',
        templateUrl: '/Scripts/App/Html/ProductList.html'
    }).
    when('/testprice', {
        controller: 'ProductController',
        templateUrl: '/Scripts/App/Html/ProductDetail.html'
    }).
    when('/editar/1', {
        controller: 'ProductController',
        templateUrl: '/Scripts/App/Html/ProductDetail.html'
    }).
    when('/api/productdetail/salvar/*', {
        controller: 'ProductDetailController',
        templateUrl: '/Scripts/App/Html/ProductDetail.html'
    })
    .otherwise({ redirectTo: '/' });

}]);

The problem in the service is when I am adding to type data: something in I am recieving in the webService null and I have to add my data in the complet uri, something like:

http//.../api/productdetail/salvar/{mydata}

using it, it is working.

what is wrong?

7
  • What is the value of mydata when the $http invokes the service? Commented Aug 4, 2015 at 10:12
  • it is a product class which I convert it to JSON.stringfly Commented Aug 4, 2015 at 10:14
  • Nope. It won't work then, since your parameter is a string type in your controller. It would always be null. Commented Aug 4, 2015 at 10:16
  • 1
    @Turbulence Wrong, you can url-encode a json and send as part of the query string. It's a bad idea, but sometimes you need to do so to cover som edge cases... Commented Aug 4, 2015 at 10:18
  • @MatiasFidemraizer - Thanks for the info. Let me edit the comment. Commented Aug 4, 2015 at 10:19

2 Answers 2

3

If you want to receive plain text from HTTP/POST body you need to apply [FromBody] attribute to controller action's input parameter:

[Route("api/productdetail/salvar")]
[HttpPost]
public bool Salvar([FromBody] string item)
{
    return true;
}

While you can go this way, WebAPI expects you to design a DTO and receive POST data using a DTO instance (WebAPI deserializes the JSON into the parameter based on its type):

[Route("api/productdetail/salvar")]
[HttpPost]
public bool Salvar(MyData item)
{
    return true;
}

MyDatamight look like this:

public class MyData
{
     public string Text { get; set; }
}

And your Angular app should send a JSON like this: { "Text": "hello world" }.

Finally, WebAPI enforces RESTful API development and your route is RPC-style. You should rename it to api/product/details and POST data to this resource URI. Otherwise, you're not designing a RESTful API!

Remember that REST loves using HTTP verbs to express actions:

  • POST is create.
  • PUT is update.
  • GET is get all, get by pages or get by id.
  • DELETE is delete by id, range, whatever.
  • ...

In summary, don't put verbs in resource URIs but use HTTP verbs to express what to do against your exposed resources.

Sign up to request clarification or add additional context in comments.

6 Comments

It is working fine. Just a question. Is it possible to convert in javascript to Base4 and in the parameter of converted it to the dto mydata automatically decoded from base64?
@David First part is done using btoa, the other part would be harder, because you would need to implement a custom parameter binding... Why you need to send base64-encoded...?
well maybe I am thinking in the old suystems which we needed security, I dont know if it is necessary now
@David Base64 provides no security. It's used to avoid special characters when sending strings over the wire, but you need to pay attention to the fact that a Base64 increases the amount of data to send/receive. Use HTTPS to secure client-server data exchange!
@David Look for custom http parameter binding on WebAPI docs. You'll need to provide a IHttpParameterBinding implementation and configure it in HttpConfiguration. BTW, ask a new question. Comments are here to resolve current answer's content issues :)
|
1

Just Food For Thought that got me. If you have a property that is being set to an invalid type like a string being set to an object in json. The api will not translate anything and you will get a null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.