c# - 网络错误: 405 Method Not Allowed in WCF

标签 c# wcf rest jquery

我尝试使用 Jquery ajax 调用来调用 WCF REST 服务方法并收到类似的错误

"NetworkError: 405 Method Not Allowed - http://localhost:55911/Service1.svc/Testing"

这是我的代码

  $(document).ready(function () {
            $("#Button2").click(function () {
                 var Input = {
                     UserId: "11111"
                             };
                $.ajax({
                    type: "POST",
                    url: " http://localhost:55911/Service1.svc/Testing",
                    data: JSON.stringify(Input),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("Success");
                    },
                    error: function (xhr, status, error) {
                        alert("failure");
                        alert(stattus.toString);
                    }
                });

            });
        });

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/Testing", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string Testing(int UserId);

  public string Testing(int UserId)
        {
            sqlConn = new SqlConnection(connectionString);
            sqlConn.Open();
            sqlCmd = new SqlCommand("TestInsertion", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.Add("@id",UserId);
            sqlCmd.ExecuteNonQuery();
            sqlConn.Close();
            return "true";
        }

我在这里做错了什么?有什么建议吗?

编辑:评论 //contentType: "application/json" 后,它正在发布并抛出

"NetworkError: 400 Bad Request - http://localhost:55911/Service1.svc/Testing"

最佳答案

  • 请检查客户端的 HTTP 请求方法是否为 POST (html) 和服务器上 (WCF 服务)
  • 因为网络错误 405 状态表明调用代码 (html) 使用了错误的 HTTP 方法,WCF 服务工作正常。

请引用:405 Method Not Allowed Error in WCF

更新

我相信是保留其余的内容(还有内容类型 contentType: "application/json"),因为它只是将参数类型更改为 来自 WCF 服务

int 的字符串
    public string Testing(string UserId)
    {
        sqlConn = new SqlConnection(connectionString);
        sqlConn.Open();
        sqlCmd = new SqlCommand("TestInsertion", sqlConn);
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.Add("@id",UserId);
        sqlCmd.ExecuteNonQuery();
        sqlConn.Close();
        return "true";
    }

关于c# - 网络错误: 405 Method Not Allowed in WCF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14827951/

相关文章:

C# - OleDbConnection.Open() 导致崩溃

c# - 使用简单进样器根据需要加载装配体

c# - WCF 中 MSI 包的自动更新

java - 在 Spring 中解析复杂的 JSON 请求

.net - 如何解决 "InvalidOperationException:operation must have a single parameter whose type is Stream"

c# - 如何将生成的网格添加到另一个生成的 child ?

c# - Wpf 托管 Windows 窗体 - 鼠标事件未通过

wcf - 开源 Web 服务/WCF 媒体流

sql - 如何从数据库中选择数据并通过WCF服务返回它?

eclipse - tomcat 上的 java web 服务 (jersey) 仅在从 eclipse 运行时才有效