bogdan.rusu
bogdan.rusu

Reputation: 943

400 bad request for http post request in .NET MVC API controller

I've read many tutorials but I can't figure it out why I get a 400 bad request on a Post request.

My Api controller:

public class CategoryApiController : ApiController {

    [HttpGet]
    [ActionName("get")]
    public int GetSomething () {
        return 1;
    }

    [HttpPost]
    [ActionName("post")]
    public string PostSomething (int id) {
        return "2";
    }
}

My routes:

routes.MapRoute (
            "ControllerOnly",
            "api/{controller}"
            );

        routes.MapRoute (
            "ControllerAndId",
            "api/{controller}/{id}",
            new {
                id = UrlParameter.Optional
            }
        );

        routes.MapRoute (
            "ControllerAndActionAndId",
            "api/{controller}/{action}/{id}",
            new {
                id = UrlParameter.Optional,
                action = "AddSomething"
            }
        );

And my ajax request :

$('#click').click(function () {
    $.ajax({
        url: '/api/CategoryApi/get',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (response) {
            $('#raspuns').text(JSON.stringify(response));
        }
    });
});

$('#raspuns').click(function () {
    $(this).text("nimic");
    $.ajax({
        url: '/api/CategoryApi/post',
        type: 'POST',
        //contentType: 'application/json; charset=utf-8',
        //dataType: 'json',
        data: {
            'id': 1
        },
        success: function (response) {
            $('#click').text(JSON.stringify(response));
        }
    });
});

So the GET request works fine but the POST request return a 400 status. The explicit message from the post request :

{"Message": "The request is invalid.", "MessageDetail": "The parameters dictionary contains a null entry for parameter 'id' of non-  nullable type 'System.Int32' for method 'System.String PostSomething(Int32)' in  'stackoverflow.Controllers.CategoryApiController'. An optional parameter must be a reference type, a   nullable type, or be declared as an optional parameter."}

The request body contains id:1. So I sent the id as parameter.

Get request is sent to the first method as expected but I don't understand why the Post request isn't working.

EDIT: So what I want is to have full control over which method is invoked in a particular controller. In JAVA, you just specify the url above the desired method and that method will be invoked when the url in accessed. I really don't understand how do I do that in .NET MVC with routes. I want to have in a single controller many GET and POST methods. Can someone give me an example or a good tutorial? PS: I've read some tutorials but there wasn't what I want.

Upvotes: 3

Views: 11444

Answers (1)

Eris
Eris

Reputation: 7638

I think the issue here is that the parameter on the actual PostSomething method is not optional. You need to either set a default value, or make it nullable.

Examples:

public string PostSomething (int? id) {

or

public string PostSomething (int id = -1) {

Alternatively, if you want the id to be required, you need to update the call to match the route:

$('#raspuns').click(function () {
    $(this).text("nimic");
    $.ajax({
        // Since your route is "api/{controller}/{action}/{id}", 
        // add the id to the url
        url: '/api/CategoryApi/post/1',
        type: 'POST',
        success: function (response) {
            $('#click').text(JSON.stringify(response));
        }
    });
});

I don't remember enough JS to make the id a variable in the URL string.

Upvotes: 1

Related Questions