0

was writing an MVC application over the weekend and decided that part of the application should use WebAPI, i had the following javascript which calls a simple MVC Controller action

    $.post("/App/TestDb", request, function (data) {
        if (data.status == "SUCCESS") {
            alert(data.msg);
            $("#installBtn").removeAttr("disabled");
        } else {
            alert(data.msg);
        }
    }, "json");

When this returns the value data is represented as a JSON object. When i ported my code over to WebAPI the result in data was a string (i.e. "{\"status\":\"SUCCESS\",\"msg\":\"Test\"}")

The MVC controller method below (removed other code to keep example simple)

public string TestDb(string appDb, string appUsername, string appPassword, string appHost)
    {
        return JsonConvert.SerializeObject(new { status = "SUCCESS", msg = "Test" });
    }

And the WebAPI controller method below

[HttpPost]
public string TestDb([FromBody] TestDbDTO testDb)
    {
        return JsonConvert.SerializeObject(new { status = "SUCCESS", msg = "Test" });
    }

As you can see from the above examples, both methods return exactly the same result. I am not sure if this is something i have (or have not) done correctly so my question is has anyone else encountered this?

Cheers

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Neil Stevens
  • 3,534
  • 6
  • 42
  • 71

1 Answers1

0

Try to rewrite your API method like this:

[HttpPost]
public object TestDb([FromBody] TestDbDTO testDb)
{
    return new { status = "SUCCESS", msg = "Test" };
}
rtf_leg
  • 1,789
  • 1
  • 15
  • 27