Reputation: 6689
I have a WCF Service (called "myservice.svc") that takes a message from a user and saves it to the database. It returns a response to the user in the form of a number. This operation looks like this:
[OperationContract]
[WebGet]
public string SubmitMessage(string message)
{
try
{
// SAVE TO DATABASE
return "1";
}
catch (Exception ex)
{
return "0";
}
}
I want to call this operation from some JQuery. I'm using the approach shown here:
$.getJSON(
"/services/myService.svc",
{message:"some text"},
function (data) {
alert("success");
}
);
Oddly, the "success" alert is never displayed. In addition, I have set a breakpoint in my WCF service and it is never being tripped. What am I doing wrong?
Thank you
Upvotes: 2
Views: 1242
Reputation: 122624
That WebGet
shouldn't be there, and you shouldn't be using the jQuery getJSON
function. This method modifies the database; it is a POST
method, not GET
.
See this page for an example of creating a POST
method. Mainly it involves adding these headers to the method:
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
You also need to make sure that you make the call correctly from jQuery, which includes setting the contentType
and other fields; the way you're making the call actually isn't valid, you're just passing raw text to the method, not a valid query string or valid JSON.
Also, you're using the wrong URL; you don't want to be posting to the endpoint, you need to post to the specific method, you have to append that to the URL. Again, the linked page should help explain all of this.
Here's an example of a correct jQuery Ajax post:
$.ajax({
url: "/services/myservice.svc/SubmitMessage",
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ \"message\": \"test\" }",
dataType: "json",
success: function(data) {
// do something
}
});
Upvotes: 6
Reputation: 20842
In addition to Aaron's answer, your URL is wrong, anyway.
If this is a WCF service, the URL you call isn't "/services/myService.svc"; you need to call the actual method URL. Since your sample above doesn't show the class name of your service, I cannot tell, but it is usually
/services/ServiceClass/MethodName
Use a browser to view the top-level service WSDL and find the actual URL paths for your methods.
Upvotes: 1