【问题标题】:Failed to load resource: the server responded with a status of 405 () and mysterius input加载资源失败:服务器响应状态为 405() 和 mysterius 输入
【发布时间】:2020-11-25 09:48:36
【问题描述】:

我有这个功能

function AddComment(id) {
    var input = $("#" + "CommentOnPost" + id).val();
  
    var commentHolder = $("#commentDiv" + id);
    commentHolder.empty();

    $.ajax({
        url: 'Account/AddCommentToPost',
        data: { postId: id, text:input },
        dataType: 'json',
        cache: false,
        success: function (result) {
            //irrelevant
        },
    });
}

但是在调试它时,我可以看到它发出了以下请求:

https://localhost:44398/Account/AddCommentToPost?postId=1&text=gd&_=1596616234410

那个额外的参数“_”不应该存在并且可能导致问题?

【问题讨论】:

  • A 405 表示服务器匹配 URL 但不匹配方法。也许您的服务器期待一个 POST 请求而不是 GET
  • _ 被 jQuery 添加为缓存破坏器,通常是一个好主意。它不会引起问题。见Who Add “_” Single Underscore Query Parameter?
  • @Phil 是的,添加 type:"POST" 解决了它。忘记这一点真是太愚蠢了。

标签: javascript ajax asp.net-core


【解决方案1】:

如果您将[HttpPost] attribute 应用于某个操作,这将标识您的操作仅支持 HTTP POST 方法。您的 Ajax 代码 sn-p 会发出 'GET' 请求,这会导致 "405 Method Not Allowed" 错误。

如您所述,要修复它,您可以尝试使用“POST”设置type 选项。

$.ajax({
    url: 'Account/AddCommentToPost',
    type: 'POST',
    //...

或从您的操作方法中删除 [HttpPost] 属性,使其支持 GET 和 POST 请求。

【讨论】:

    猜你喜欢
    • 2021-08-26
    • 2018-12-16
    • 1970-01-01
    • 2018-06-18
    • 2014-12-01
    • 2020-02-14
    相关资源
    最近更新 更多