Reputation: 361
I published on my Windows Server a WCF Service on IIS 7.5
It has basically two methods, just for the smoke test .
Here the ServiceContract:
[ServiceContract]
public interface IFSMServiceWeb
{
[OperationContract]
[WebInvoke(Method="POST", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json)]
string registraUtenteViaMail(string username, string password, string key, string dbVersion);
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
string loginUtenteViaMail(string username, string password, string key, string dbVersion);
}
and here the implementation:
public class FSMServiceWeb : IFSMServiceWeb
{
public string registraUtenteViaMail(string username, string password, string key, string dbVersion)
{
return username + password + key + dbVersion;
}
public string loginUtenteViaMail(string username, string password, string key, string dbVersion)
{
return username + password + key + dbVersion;
}
}
I have no problem to call the method call loginUtenteViaMail with GET, but I cannot call method registraUtenteViaMail with POST method.
Here javascript code used to test POST method
$(document).ready(function(){
$("#send").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var key = $("#key").val();
var dbVersion = $("#dbVersion").val();
var dati = {username : username, password : password, key : key, dbVersion : dbVersion};
$.ajax({
type: 'POST',
url: '/FSMServiceWeb.svc/registraUtenteViaMail',
data: JSON.stringify(dati),
success: function (data) {
console.log(data);},
error: function (data){},
dataType: 'JSON'
});
});
});
I obtain this error (Chrome Console):
POST http://xxx.xxx.xxx.xxx/FSMServiceWeb.svc/registraUtenteViaMail 400 (Bad Request) jquery.min.js:4
l.cors.a.crossDomain.send jquery.min.js:4
o.extend.ajax POSTtest.js:12
(anonymous function) jquery.min.js:3
o.event.dispatch jquery.min.js:3
r.handle jquery.min.js:3
Where am I wrong?
Thank you in advance
Upvotes: 2
Views: 2621
Reputation: 361
No way! I figured out the problem. I miss an important part of my AJAX request:
contentType: "application/json; charset=utf-8",
In fact correct request should be this one:
$(document).ready(function(){
$("#send").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var key = $("#key").val();
var dbVersion = $("#dbVersion").val();
var dati = {username : username, password : password, key : key, dbVersion : dbVersion};
$.ajax({
type: 'POST',
url: '/FSMServiceWeb.svc/registraUtenteViaMail',
contentType: "application/json; charset=utf-8", // MISSING PART!
data: JSON.stringify(dati),
success: function (data) {
console.log(data);},
error: function (data){},
dataType: 'JSON'
});
});
});
Upvotes: 3