我有標準的asmx web服務返回JSON:POST到JSON webervice將返回錯誤500
private void ReturnUser(string name)
{
User user = new User(name);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, @object);
string jsonString = Encoding.UTF8.GetString(stream.ToArray());
stream.Close();
HttpContext.Current.Response.AddHeader("ContentType", "application/json");
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Write(jsonString);
HttpContext.Current.Response.End();
}
在另一邊,我想嘗試的是Web服務正在運行,所以我嘗試撥打POST:
string data = "name=test";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
WebRequest request = WebRequest.Create("http://tempuri.org/External.asmx?op=ReturnUser");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataStream.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(dataStream, 0, dataStream.Length);
reqStream.Close();
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string json = reader.ReadToEnd();
stream.Close();
reader.Close();
Console.Write(json);
Console.Read();
,但我得到錯誤500從瀏覽器的Web服務運行就像一個魅力:(
錯誤500有時在你的.asmx方法所造成的錯誤的。檢查使用的認證。 – GiantHornet
只是好奇,但你爲什麼手動序列化到JSON和直接寫入響應?如果它是ASMX服務並且從返回值中獲得JSON響應,您應該可以將其添加到方法中:[ScriptMethod(ResponseFormat = ResponseFormat.Json)] –
我試圖使用[ScriptMethod(ResponseFormat = ResponseFormat.Json) ]但它返回XML。後來才知道它只能用於AJAX或jQuery,但我打算從非移動設備中調用它。 –