我有标准的 asmx webservice 返回 Json:
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();
}
另一方面,我想尝试 webservice 正在运行,所以我尝试调用 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 服务就像一个魅力:(