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 に答える