Pass int to webapi

I know this has been asked a thousand times. But I can't find my error. I narrowed it down by testing it without a parameter, which worked and then tried various things. Like, get or post, [FromBody] or not. etc. Perhaps I should just show my code or I should stop for today and just celebrate that it is almost weekend.

[HttpGet] // also tried post instead of get
public HttpResponseMessage Get(int id)
{
    return Request.CreateResponse(HttpStatusCode.OK); // breakpoint set, not hit
}

My Js code:

var myObj = {};
myObj["id"] = parseInt(id);

var json = JSON.stringify(myObj);
alert(json);  // display: { id = 2134 }, seems fine to me

$.ajax({
    type: "GET", // also tried post
    dataType: "json",
    url: '/api/CheckPossible/Get',
    data: json,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function () {
        alert('success');
    },
    error: function () {
        alert('failure');
    }
});

I have received a lot of bad requests (400) and I did got it to work without a parameter. So it is not a routing issue.

edit

$.ajax({
    type: "GET",
    dataType: "json",
    url: '/api/CheckPossible/Get/?id=1234', // also tried Get?id=1234
    contentType: "application/json; charset=utf-8",
    success: function () {
        alert('success');
    },
    error: function () {
        alert('failure');
    }
});

Did not work. Perhaps I am missing something else too

1 answer

  • answered 2017-11-17 11:48 Igor

    You can't pass a http message body to a GET method, you have to pass parameters either in the URL or in the header. For a web api you should pass them in the URL and you can do this as a query string or as part of the URL.

    To get it to work with the query string change the url to

    url: '/api/CheckPossible/?id=' + myObj["id"],
    

    leave out the data as this won't do anything with get.

    If you want to make the parameter a part of the URL then change your route to include it. I prefer the Route attribute for flexible routing, you can also change the global routing scheme.

    [HttpGet] // also tried post instead of get
    [Route("api/CheckPossible/{id:int}"]
    public HttpResponseMessage Get(int id)
    {
    }
    

    and change your url to

    url: '/api/CheckPossible/' + myObj["id"]