1

我在 .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);

这项工作,但我想知道是否有更好的方法,或者我怎样才能使请求异步。谢谢。

4

2 回答 2

1

看看WebClient课堂。此外,您可能应该使用GET请求来检索数据。

    // Create web client.
    WebClient webClient = new WebClient();

    // Download your XML data
    string xmlData= webClient.DownloadString("MyAspxPage.aspx/GetSomeInformation");
于 2010-09-26T13:24:56.100 回答
0

如果调用代码与定义 WebMethod 的文件在同一个应用程序中,则可以将其重构为实用程序类并像任何其他方法一样调用它。[WebMethod] 将其作为服务公开,但不会消除您从代码中使用它的能力。

于 2010-09-26T13:44:48.320 回答