POST 使用 Jquery 的 $.post() 请求,405 方法不允许

POST Request with Jquery's $.post(), 405 Method Not Allowed

我在 C# 控制器中设置了一个异步任务,如下所示:

命名空间MyApp.Api {

public class TimeAllocationController : BaseApiController
{
    [Route("api/timeallocation")]
    [HttpPost]
    public async Task<ActivityValidationResult> Post(string id)
    {
        //logic here...
    }

理想情况下,我想使用 $.post() 方法在 JQuery 中传递整个有效负载,但如果

我一直收到 405 method not allowed

我尝试在有效负载中传递 C# 的 Post() 字符串 ID。我只能这样传入:

$.post('/api/timeallocation/' + categoryId...

我不能像这样传递它:

$.post('/api/timeallocation?id=' + categoryId...

我不想做以上任何事情,只需在 JS 文件中设置一个 payload 变量,其中包含 id 和所有其他必需的属性,然后调用 $.post()

至于405错误的其他可能原因,我已经确认不是认证原因。

我在这里忽略了什么吗?

你应该打电话给

$.post('/api/timeallocation/', categoryId)

或者你可以添加id参数的[FromUri]属性并调用

$.post('/api/timeallocation?id' + categoryId)
public class TimeAllocationController : BaseApiController
{
    [Route("api/timeallocation")]
    [HttpPost]
    public async Task<ActivityValidationResult> Post(JObject json)
    {
        string id = json["id"];
        //login here
    }
}

or

public class TimeAllocationController : BaseApiController
{
    [Route("api/timeallocation")]
    [HttpPost]
    public async Task<ActivityValidationResult> Post(dynamic json)
    {
        string id = json.id ?? "";
        //login here
    }
}

$.ajax({
    url: "/api/timeallocation/",
    dataType: "json",
    type: "POST",
    data: {
        id: categoryId
    }
});

如果你想用来自 jquery 的有效载荷调用它,你应该让你的 Post 方法带有 [FromBody] 属性,如下所示:

public class TimeAllocationController : BaseApiController
{
    [Route("api/timeallocation")]
    [HttpPost]
    public async Task<ActivityValidationResult> Post([FromBody] string id)
    {
        //logic here...
    }

See the documentation

然后你可以用

调用它
$.ajax({
    url: "/api/timeallocation/",
    dataType: "json",
    type: "POST",
    data: {
        id: categoryId
    }
});

我能够在我的控制器中使用以下方法解决它:

public async Task<ActivityValidationResult> Post(string id, [FromBody] TimeAllocationActivity payload)

其中 payload 处理 TimeAllocationActivity 属性。请注意,我确实必须创建 TimeAllocationActivity 模型,因为它以前不存在。

在 JS 方面,我创建了 payload 变量,然后像这样设置请求:

processCheckAjax = $.ajax({
    url: "/api/timeallocation/" + categoryId,
    dataType: "json",
    type: "POST",
    data: JSON.stringify(payload)

我确实觉得很奇怪,我仍然必须将 categoryId 附加到路由,但它不能包含在有效负载中。