我試圖從JSON格式的c#應用程序調用Web服務(.asmx)。Web服務拒絕接收參數並以JSON格式回覆
當我指定請求方法爲GET,並且不指定contentType。
(REQ是HttpWebRequest的)
req.Method = "GET";
一切運作良好,但我得到XML響應。
當我指定的內容類型:
req.ContentType = "application/json; charset=utf-8";
我得到
500內部服務器錯誤。
當我改變請求方法:
req.Method = "POST";
我只能調用參數的方法,它返回正確的json,但如果我嘗試調用帶有參數的方法,我再得到500錯誤。
Web服務代碼:
[WebMethod(EnableSession =true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SimplestWebService()
{
return "hello";
}
,並與參數:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Echo(string aString)
{
return aString;
}
任何想法將非常感激。
加入:也許我沒有寫POST請求的權利(現在我發送它的頭,就像一個GET請求)。有人能指導我嗎?
模式補充說:該網站確實被標記爲腳本:
[ScriptService]
public class MyAPI : System.Web.Services.WebService
,這裏是我如何建立我的POST請求(我真的傾向於認爲這就是問題所在):
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());
}
...
也試過:
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();
最後兩個注意事項:
1.此Web服務使用瀏覽器以XML格式工作。
2.詢問json,代碼從未到達Web服務的中斷點。所以這可能是一個IIS(我使用IIS 6.1)的問題。我試過MIME類型推薦here。
非常感謝。
您可以在代碼中配置輸出請求嗎?具體來說,你如何添加「aString」參數?這可能有助於調試問題。 – mikemanne 2010-10-06 19:42:36
另外,ASMX類本身的標籤是:[ScriptService]?我認爲(不是100%肯定),這是使用POST模式請求和JSON格式的數據訪問Web服務所必需的。 – mikemanne 2010-10-06 19:45:08
@mikemanne:非常感謝您的意見。更新。 – 2010-10-06 20:07:56