I am trying to call WCF REST service method using Jquery ajax call and getting an error like
"NetworkError: 405 Method Not Allowed - http://localhost:55911/Service1.svc/Testing"
Here is my code
$(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);
}
});
});
});
and
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/Testing", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string Testing(int UserId);
and
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";
}
What am i doing wrong here??Any suggestion??
EDIT:After commenting //contentType: "application/json"
it is posting and throwing
"NetworkError: 400 Bad Request - http://localhost:55911/Service1.svc/Testing"
POST
at client (html
) and on server (WCF service
)html
) is using wrong HTTP Method,WCF service
is working ok.Please refer: 405 Method Not Allowed Error in WCF
Update
What I believe is keep the rest of the things (also content type
contentType: "application/json"
) as it is just change parameter type tostring
fromint
inWCF service
Are you running both WCF Service Project and Consuming Project (AJAX Call) at the same time (in same instance of Visual Studio)? If so, try two different VS instances and run WCF Project first, then the consuming project. Also, try using
dataType
asjsonp
instead ofjson
.Check whether the HTTP Request method is POST or OPTIONS. This link will be useful.
I think you need to use JSONP for a cross-domain call to get round the browser restrictions
this answer is very helpful: WCF error : 405 Method Not Allowed
The
UriTemplate
you defined is wrong, try using it like this:and then in the implementation convert that
UserId
to int as you wanted.Usually this errors happens when an exception is thrown at your method so i suggest to debug
it either by attaching it to process to by writing this line of code at the beginning of the
function