Hi.
I have a WebMethod inside an .aspx:
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public static XmlDocument GetSomeInformation()
{
XmlDocument Document = new XmlDocument()
// Fill the XmlDocument
return Document;
}
It works great when i call it with 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);
}
Well, I want to do exactly what JQuery is doing, but in c#...
I'm using this:
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);
This work, but I would like to know if there is a better way, or how can i make the request asyncronous. Thanks.