【发布时间】:2011-04-21 07:31:13
【问题描述】:
我正在尝试从 c# 应用程序以 json 格式调用 Web 服务 (.asmx)。
当我将请求方法指定为 GET 并且不指定 contentType 时。
(req 是 HttpWebRequest)
req.Method = "GET";
一切正常,但我得到了 XML 响应。
当我指定内容类型时:
req.ContentType = "application/json; charset=utf-8";
我明白了
500 内部服务器错误。
当我更改请求方法时:
req.Method = "POST";
我只能调用无参数方法,它会正确返回 json,但如果我尝试调用 带有 参数的方法,我会再次收到 500 错误。
网络服务代码:
[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”参数?这可能有助于调试问题。
-
另外,ASMX 类本身是否标记为:[ScriptService]?我认为(不是 100% 肯定)使用 POST 模式请求和 JSON 格式的数据访问 Web 服务是必要的。
-
@mikemann:非常感谢您的意见。已更新。
标签: c# asp.net web-services asmx