【发布时间】:2014-09-04 03:47:43
【问题描述】:
我已将 Json 发送到 Web 方法。虽然 web 方法没有将 json 作为字符串接收。
POST 方法 Test1.aspx -
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:49633/Test3.aspx/Get");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"d\":{\"accessKey\":\"Chennai\",\"channelId\":\"1025\"}}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
return responseText;
}
Test3.aspx中的WEB方法
[System.Web.Services.WebMethod]
public static string Get(string d)
{
return d;
}
回应 -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form name="form1" method="post" action="Booking.aspx" id="form1">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTg3NjI4NzkzNmRkOvsswBe8G74mfKP2QBvs0WW2jms=" />
<div>
<span id="Label3"><font color="Fuchsia">Responce:-</font></span>
<span id="Label1">Label</span>
</div>
</form>
</body>
</html>
查询 -
我收到作为 HTML 页面的响应。但我想接收我通过 POST 方法发送的 Json
JSON 字符串 -
{"d":{"accessKey":"Chennai","channelId":"1025"}}
编辑
我已将json字符串更改为{"accessKey":"Chennai","channelId":"1025"},并更改了获取字符串的webmethod。
[System.Web.Services.WebMethod]
public static string Get(string accessKey, string channelId)
{
return accessKey + channelId;
}
我收到了正确的 channelId、accesskey 值。但是我的原始字符串非常大。所以我需要接收我通过 POST 方法发送的相同的 Json 字符串。 bzs 我只做接收部分。我的客户有一次通过调用此 Websmethod 发送 Json 字符串。谢谢。
编辑 2-
按照 Mez 所说,我已经包含了 ScriptMethod。但是它通过远程服务器返回了一个错误:(500) Internal Server Error.
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Get(string d)
{
return d;
}
【问题讨论】:
-
考虑使用 HTTP 通用处理程序。查看链接:stackoverflow.com/questions/3702959/…。它将避免发回您不需要的内容,例如您的情况……
-
当我将字符串更改为 {"accessKey":"Chennai","channelId":"1025"} 并将 webmethod 更改为 public static string Get(string accessKey, string channelId) 我可以得到价值。但我想要一个 Json Full String,。
-
您还缺少 ScriptMethod 响应格式...
-
见我更新的问题先生。我已包含 ScriptMethod,但出现错误。