Reputation: 1633
I have ASMX webservice and I want to return the result in JSON format. Its working fine when my web method is without parameters.
[WebService(Namespace = "http://www.arslanonline.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 AuthService : System.Web.Services.WebService {
public AuthService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string Authenticate(string username, string password, string appId)
{
return ToJson("Hello World");
}
public static string ToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Test()
{
return ToJson("Hello World");
}
When I am calling My Test Web Method This Way Its Working Fine
string url= "http://localhost:45548/Moves/AuthService.asmx/Test";
string dataToPost= "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json;";
request.BeginGetRequestStream(new AsyncCallback(DoHTTPPostRequestReady), new HttpWebRequestData<string>()
{
Request = request,
Data = dataToPost
});
and returning my JSON result. But for my second method Authenticate that is taking some parameters I am requesting like that
string url= "http://localhost:45548/Moves/AuthService.asmx/Authenticate";
string dataToPost= "username=ABC&password=123&appid=1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json;";
request.BeginGetRequestStream(new AsyncCallback(DoHTTPPostRequestReady), new HttpWebRequestData<string>()
{
Request = request,
Data = dataToPost
});
and its giving me Not Found Error
But When I Change to request.ContentType = "application/x-www-form-urlencoded"
; It works fine and returns me result in XML but not in JSON format. Why this is happening Can Please anyone tell where is the glitch in my code.
Upvotes: 1
Views: 4092
Reputation: 1240
Use void as return type for the method.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Test()
{
System.Web.HttpContext.Current.Response.Write(ToJson("Hello World"));
}
Upvotes: 4