我在使用通用处理程序调用方法时遇到了一些麻烦。我尝试使用两种不同的技术来调用一个简单的'HelloWorld()'方法,但我得到两个不同的错误:
第一种技术如下:
WebClient wc = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["method"] = "HelloWorld";
byte[] data;
try
{
data = wc.UploadValues(_domain, formData);
}
catch (WebException ex)
{
Label1.Text = ex.Message;
return;
}
string response = Encoding.UTF8.GetString(data);
Label1.Text = response;
wc.Dispose();
我收到以下错误:
{"id":null,"error":{"name":"Found String where Object was expected."}}
我尝试的第二种技术是:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(_domain);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"method\":\"helloWorld\"}"; //," +
//"\"password\":\"bla\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (WebException wex)
{
Label2.Text = wex.Message;
}
catch (Exception ex)
{
Label2.Text = ex.Message;
}
}
由此,我收到以下错误:
The remote server returned an error: (500) Internal Server Error.
当我从“.ashx?test”页面测试调用时,该方法运行,屏幕底部的详细信息为:
Pragma: no-cache
Date: Tue, 23 Jul 2013 13:46:19 GMT
Server: ASP.NET Development Server/11.0.0.0
X-AspNet-Version: 2.0.50727
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
Connection: Close
Content-Length: 32
Expires: -1
关于为什么这不起作用的任何想法?
谢谢!
答案 0 :(得分:4)
ASHX处理程序不是Web服务。您不在ASXH处理程序中调用方法。您只需调用处理程序,它就可以直接传递数据,无论是文本数据还是二进制数据 - 这取决于您。