简体   繁体   English

在.NET MVC API控制器中对400 post请求的错误请求

[英]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. 我已经阅读了很多教程,但我无法弄清楚为什么我在Post请求上收到400错误请求。

My Api controller: 我的Api控制器:

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 : 我的ajax请求:

$('#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. 所以GET请求工作正常,但POST请求返回400状态。 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. 请求正文包含id:1。 So I sent the id as parameter. 所以我发送了id作为参数。

Get request is sent to the first method as expected but I don't understand why the Post request isn't working. 获取请求按预期发送到第一个方法,但我不明白为什么Post请求不起作用。

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. 在JAVA中,您只需在所需方法上方指定url,并在访问url时调用该方法。 I really don't understand how do I do that in .NET MVC with routes. 我真的不明白我如何在带有路由的.NET MVC中做到这一点。 I want to have in a single controller many GET and POST methods. 我希望在单个控制器中有许多GET和POST方法。 Can someone give me an example or a good tutorial? 有人可以给我一个例子或一个好的教程吗? PS: I've read some tutorials but there wasn't what I want. PS:我已经阅读了一些教程,但没有我想要的东西。

I think the issue here is that the parameter on the actual PostSomething method is not optional. 我认为这里的问题是实际的PostSomething方法上的参数不是可选的。 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: 或者,如果您需要id,则需要更新呼叫以匹配路由:

$('#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. 我不记得足够的JS使id成为URL字符串中的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM