Search code examples
javascriptasp.netajaxasp.net-web-apiasp.net-web-api-routing

Cannot get parameter when sending a post request


I'm using attribute routing. I cannot get parameters from HTTP body, can anyone please tell what's wrong here. My ConnectionID Class has a property called CValue.

$('#btn').click(function () {
    $.ajax({
        type: "POST",
        url: "http://localhost:49289/api/Resolver/StartRun",
        data: { "CValue": connectionID },
        success: success,
        dataType: "json"
    });
});



[Route("api/Resolver/StartRun")]
[HttpPost]
public async Task<string> GetStatus([FromBody]ConnectionID connectionID)
{
}

Solution

  • You are using the path which will require CORS, if you change your path to be relative:

    url: "/api/Resolver/StartRun",
    

    It should run no problem, here is the simple examples I used to demo this.

    JavaScript

    <script>
            $.ajax({
                type: "POST",
                url: "/api/Resolver/StartRun",
                data: { "CValue": "123" },
                success: new function(){},
                dataType: "json
               });
    </script>
    

    Controller

        [Route("api/Resolver/StartRun")]
        [HttpPost]
        public async Task<string> GetStatus([FromBody]ConnectionID connectionID)
        {
            return "test";
        }
    

    Class

    public class ConnectionID
    {
        public string CValue { get; set; }
    }
    

    Screen shot

    enter image description here

    You will have to take my word for the parameter being populated, on a mac and I can't remember how to take a print screen (used snipping tool) but if you run it with the above you will see. :)