我尝试使用 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/