1
votes

I have the following structure for my WEB API controller:

public class MyController : ApiController
{
   [System.Web.Http.HttpPost]
   public bool Method1([FromBody] int id, [FromBody] string token, [FromBody] string deviceID, [FromBody] string username)
   {
      bool returnValue = false;

      //do code business logic here

      return returnValue;
   }

   [System.Web.Http.HttpPost]
   public bool Method2([FromBody] int id, [FromBody] string token)
   {
      bool returnValue = false;

      //do code business logic here

      return returnValue;
   }
}

When I try to make a RESTFUL Web API over HTTP for either Method1 or Method2, I get a 500 Internal Server Error.

If I remove the input parameters from either method, I have able to make the Web API without an error.

I have unit tested the controller through a .NET test method and the logic does not generate an exception.

I have added an additional method named Get with no parameters, and was able to consume the service without any errors.

Here is a code snippet of me trying to consume the web API in JavaScript using jQuery:

var uri = "http://127.0.0.1/MyWebApi/api/mycontroller/method2";

var myObject =
{
    id: $('#id').val(),
    token: $('#token').val()
};

$.post(uri, JSON.stringify(myObject)).done(function (data) {
    $('#result').text(data);
})
.fail(function (jqXHR, textStatus, err) {
    $('#result').text('Error: ' + err);
});

What is causing me to get the 500 Internal Server Error on the initial API controller structure?

3

3 Answers

3
votes

From the documentation regarding [FromBody]:

At most one parameter is allowed to read from the message body.

So you have to create a model which matches the parameters that you post as a body.

0
votes

This 500 error is probably because it is not finding a matching Action in the server for the given parameters, considering the HTTP method you are using (POST).

Shouldn't myObject be like this? (token instead of toke)

var myObject =
{
    id: $('#id').val(),
    token: $('#token').val()
};

Also, you don't need to stringify the JSON object. If should work like this:

$.post(uri, myObject).done(function (data) {
    $('#result').text(data);
})
.fail(function (jqXHR, textStnatus, err) {
    $('#result').text('Error: ' + err);
});
0
votes

I was having the same error and it took me quite some time before I could figure out what was causing it. The easiest way is to check your response message from your browser. In IE11 you can press F12, go to network tab and start recording. Then after you call is made stop it and review the call. In my case I found out that my returned message failed to serialize due to looping links in the object I was about to receive. So within some slight tweaks on Web API side I managed to get it working just fine. So check your response - you may get more details about the error.