【发布时间】:2014-01-25 09:42:47
【问题描述】:
$.ajax({type: "post",
url: "http://test.com/Register",
data: {
"UserID": '12',
"FirstName": 'FN1'
},
accept: {
json: "application/json",
jsonp: "application/javascript"
},
dataType: "jsonp",
crossDomain: true,
beforeSend: function (xhr) {
xhr.withCredentials = true;
},
xhrFields: {
withCredentials: true
},
cache: false,
success: function (data) {
if(data.success)
{
alert("success");
}
else
{
alert("failed");
}
}
});
我有这个使用 javascript 的 Ajax 调用。 但我试图通过 C# 使用 HTTPWebRequest 进行同样的调用,但没有得到相同的结果。 当我通过 C# 进行调用时,它返回一个网页,而不是一个 json 字符串,这是不对的。之所以发生这种情况,是因为出于某种原因调用不正确。 但是 AJAX 调用会返回一个正确的 json 字符串给我。 我认为是因为ajax调用将数据类型指定为“jsonp”并指定它是跨域的。
我需要它在 C# 中工作的原因是因为我希望在 Web 服务中进行这个 C# 调用。 因此,一个表单调用了我的 Web 服务(MyWebservice.asmx),这反过来又使这个调用成为问题http://test.com/Register。 所以我不能真正将 AJAX / Jquery 写入我的 Web 服务,而宁愿使用 C# 来进行此调用。
有什么帮助吗?
string data = "[SOME JSON DATA]";
byte[] bytesArray = encoding.GetBytes(data);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://test.com/Register");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = bytesArray.Length;
using (Stream stream = httpRequest.GetRequestStream())
{
stream.Write(bytesArray, 0, bytesArray.Length);
stream.Close();
}
HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
// Read the response content.
responseFromServer = reader.ReadToEnd(); //This gives an HTML page as response
【问题讨论】:
-
JSONP 不能 POST,原因与您不能使用脚本标签或图像元素 POST 的原因相同。
<script src="http://test.com/Register?callback=jQuery61984769182746916529178256931"></script> -
Kevin,你的意思是不能用 C# 做同样的 POST 吗?
-
我对这个说法提出异议:“我有这个 Ajax 调用使用 javascript。” 如果它正在工作,它要么不是 POST,要么不是 JSONP .如果您使用 C# 发出请求,则无论如何都不需要 JSONP,您只需执行基本的 http 请求即可获取字符串响应,然后解析字符串响应。
-
C#不必遵守同源策略,因此跨域这一事实无关紧要。
-
凯文,我认为你是对的。当我检查 ajax 调用的提琴手时,即使 jquery 代码显示 POST,它也会显示 GET。我正在尝试的 HTTPWebRequest 看起来是否可疑?也许我错过了什么,因此反应错误。
标签: c# jquery ajax cross-domain jsonp