Search code examples
asp.netangularjsasp.net-mvcasp.net-web-api2angular-resource

Not getting my parameter from the body of the request


I try and hit my API Controller which I'm able to make it there. However the method is not getting my parameter from the body of the request. I know this is something small.

I've tried moving the service around adding parameters in many different ways. Nothing so far seems to work.

Key Things to Note

This is a MVC 4 application if that helps. I believe it's something in the angular syntax or possibly the controller attributes.

I'm using a HTTPPost.

Service

(function () {
'use strict';
var rmdsnewServices = angular.module('rmdsnewServices', ['ngResource']);

rmdsnewServices.factory('rmds', ['$resource',
  function ($resource) {
      return {
          rmdnewly: $resource('/api/rmd/', {}, {
              query: {
                  method: 'GET', params: {}, url: '/api/rmd/getNewly/', isArray: false,
                  transformResponse: function (data) { return { list: angular.fromJson(data) } }
              }
          }),

          rmdsave: $resource('/api/rmd/AddRMD/:newrmd', { newrmd: '@newrmd' }, {
              save: {

                  method: 'POST', params: { newrmd: '@newrmd' }

              }

          })



      };
  }]);
})();

API Controller

[Route("api/rmd/AddRMD")]
    [HttpPost]
    public HttpResponseMessage AddRMD([FromBody]string newrmd)
    {
        var rmd = newrmd;

        bool result;
        //result = rs.AddRMD(newrmd);
        result = true;
        if (result)
        {
            return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        }
        else
        {
            return new HttpResponseMessage(System.Net.HttpStatusCode.ExpectationFailed);
        }
    }

Solution

  • Your controller action expects a string. Also, your $resource doesn't need to send the :param on the url:

                          rmdsave: $resource('/api/rmd/AddRMD/', { }, {
                          save: {
                              method: 'POST'
                          }
                      })
    

    Then sending simply a string, will hit your controller:

            angular.module('rmdsnewServices').controller('MyController', ['rmds', function (rmds) {
            this.click = function() {
                rmds.rmdsave.save("'asd'");
            }
        }]);
    

    To send an object instead of the string:

    rmds.rmdsave.save({Name:"someName"});
    
    
    
      public class Test
        {
            public string Name { get; set; }
        }
    
        public class rmdController : ApiController
        {
            [HttpPost, Route("api/rmd/AddRMD")]
            public HttpResponseMessage SomePath([FromBody] Test newrmd)
            { ...