I'm trying to call a web service (.asmx) from a c# application, in json format.
When I specify request method as GET, and don't specify contentType.
(req is HttpWebRequest)
req.Method = "GET";
Everything works well, but I get XML response.
When I specify content Type:
req.ContentType = "application/json; charset=utf-8";
I get
500 internal server error.
When I change request method:
req.Method = "POST";
I can call parameterless methods only, which returns correctly json, but if I try calling a method with parameters, I get 500 error again.
The web service code:
[WebMethod(EnableSession =true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SimplestWebService()
{
return "hello";
}
And With parameters:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Echo(string aString)
{
return aString;
}
Any ideas will be much appreciated.
Added: Maybe I'm not writing the POST request right (now I'm sending it in the header, just like a GET request). Can someone please guide me on that?
Mode added: The web site is indeed marked as script:
[ScriptService]
public class MyAPI : System.Web.Services.WebService
And here is how I build my POST request (I really tend to believe that's the problem):
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(methodUrl.ToString());
req.Method = "POST";
req.Headers.Add("aString","oren");
req.ContentLength = 0;
...
req.ContentType = "application/json; charset=utf-8";
req.Accept = "application/json; charset=utf-8";
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
StreamReader sr = new StreamReader(res.GetResponseStream());
result.Append(sr.ReadToEnd());
}
...
Also tried:
req.Method = "POST";
string postData = "aString=kjkjk";
req.ContentType = @"application/json; charset=utf-8";
req.Accept = @"application/json; charset=utf-8";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
req.ContentLength = byte1.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
Two last notes:
1. This web service works in XML using the browser.
2. Asking for json, the code never reaches a break point at the web service. So this is possibly a IIS (I'm using IIS 6.1) issue. I've tried the MIME type recommendation here.
Thanks a lot.