我在.aspx中有一个WebMethod:
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public static XmlDocument GetSomeInformation()
{
XmlDocument Document = new XmlDocument()
// Fill the XmlDocument
return Document;
}
当我用JQuery调用它时效果很好:
TryWebMethod = function()
{
var options =
{
type: "POST",
url: "MyAspxPage.aspx/GetSomeInformation",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "xml",
cache: false,
success: function (data, status, xhr)
{
alert(formatXml(xhr.responseText));
},
error: function (xhr, reason, text)
{
alert(
"ReadyState: " + xhr.readyState +
"\nStatus: " + xhr.status +
"\nResponseText: " + xhr.responseText +
"\nReason: " + reason
);
}
};
$.ajax(options);
}
好吧,我想完成JQuery正在做的事情,但是在c#...
我正在使用它:
WebRequest MyWebRequest = HttpWebRequest.Create("http://localhost/MyAspxPage.aspx/GetSomeInformation");
MyWebRequest.Method = "POST";
MyWebRequest.ContentType = "application/json; charset=utf-8";
MyWebRequest.Headers.Add(HttpRequestHeader.Pragma.ToString(), "no-cache");
string Parameters = "{}"; // In case of needed is "{\"ParamName\",\"Value\"}"...Note the \"
byte[] ParametersBytes = Encoding.ASCII.GetBytes(Parameters);
using (Stream MyRequestStream = MyWebRequest.GetRequestStream())
MyRequestStream.Write(ParametersBytes, 0, ParametersBytes.Length);
string Result = "";
using (HttpWebResponse MyHttpWebResponse = (HttpWebResponse)MyWebRequest.GetResponse())
using (StreamReader MyStreamReader = new StreamReader(MyHttpWebResponse.GetResponseStream()))
Result = MyStreamReader.ReadToEnd();
MessageBox.Show(Result);
这项工作,但我想知道是否有更好的方法,或者我如何使请求异步。 感谢。
答案 0 :(得分:1)
查看WebClient
课程。您也可以使用GET
请求来检索数据。
// Create web client.
WebClient webClient = new WebClient();
// Download your XML data
string xmlData= webClient.DownloadString("MyAspxPage.aspx/GetSomeInformation");
答案 1 :(得分:0)
如果调用代码与您定义WebMethod的文件位于同一个应用程序中,则可以将其重构为实用程序类并像调用任何其他方法一样调用它。 [WebMethod]将其公开为服务,但不会删除您从代码中使用它的能力。