I am calling in ASP.NET 4.0 web site a web service (asmx service in same web site) method in 2 different ways. The first method succeeds and always returns a valid JSON object when the asmx web service method is decorated with [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
.
But the second method fails because the data returned is XML rather than JSON, even though I have decorated the asmx
method by [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
(I cannot understand why JSON is not being returned when using GET
but it is when using POST
?)
POST
service callvar serviceurl = "http://localhost:49441/WebService1.asmx/LoginUser" ; $.ajax({ url: serviceurl, type: 'POST', contentType: "application/json; charset=utf-8", data: JSON.stringify({ userName: userName, password: password }), dataType: "json", success: function (msg) { alert('Web service call succeeded. ' + msg.d); }, error: function (error) { alert('ERROR has occurred!'); alert(JSON.stringify(error)) } });
GET
service callvar serviceurl = "http://localhost:49441/WebService1.asmx/LoginUser" ; $.ajax({ url: serviceurl, type: 'GET', contentType: "application/json; charset=utf-8", data: 'userName='+ userName + '&password=' + password, dataType: "json", success: function (msg) { alert('Web service call succeeded. ' + msg.d); }, error: function (error) { alert('ERROR has occurred!'); alert(JSON.stringify(error)) } });
EDIT 1:
The Web Service code is as below. When using
POST
I simply change code to useUseHttpGet = false
for the method being called.[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { [WebMethod] [PrincipalPermission(SecurityAction.Assert, Unrestricted = true)] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public bool LoginUser(string userName, string password) { bool authenticated = false; if (userName.ToLower() == "mike" && password.ToLower() == "abcd") { authenticated = true; } return authenticated; } }