繁体   English   中英

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

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

我已经阅读了很多教程,但我无法弄清楚为什么我在Post请求上收到400错误请求。

我的Api控制器:

public class CategoryApiController : ApiController {

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

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

我的路线:

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"
            }
        );

我的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));
        }
    });
});

所以GET请求工作正常,但POST请求返回400状态。 来自帖子请求的显式消息:

{"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."}

请求正文包含id:1。 所以我发送了id作为参数。

获取请求按预期发送到第一个方法,但我不明白为什么Post请求不起作用。

编辑:所以我想要的是完全控制在特定控制器中调用哪个方法。 在JAVA中,您只需在所需方法上方指定url,并在访问url时调用该方法。 我真的不明白我如何在带有路由的.NET MVC中做到这一点。 我希望在单个控制器中有许多GET和POST方法。 有人可以给我一个例子或一个好的教程吗? PS:我已经阅读了一些教程,但没有我想要的东西。

我认为这里的问题是实际的PostSomething方法上的参数不是可选的。 您需要设置默认值,或使其可为空。

例子:

public string PostSomething (int? id) {

要么

public string PostSomething (int id = -1) {

或者,如果您需要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));
        }
    });
});

我不记得足够的JS使id成为URL字符串中的变量。

暂无
暂无

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

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