2010-09-26 28 views
1

我有一個.aspx裏面一個WebMethod:構建調用裏面的.aspx的WebMethods在C#中的要求

[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); 

這項工作,但我想知道是否有更好的方法,或者我如何使請求asyncronous。 謝謝。

回答

1

查看WebClient課程。你也可能應該使用GET請求來檢索數據。

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

    // Download your XML data 
    string xmlData= webClient.DownloadString("MyAspxPage.aspx/GetSomeInformation"); 
+0

但我怎樣才能發送參數與webclient? – Fraga 2010-09-26 13:31:38

+0

查看UploadValues方法,另請參閱http://stackoverflow.com/questions/1117421/webclient-uploaddata-correct-usage-for-post-request – BrokenGlass 2010-09-26 14:53:00

0

如果調用代碼是在相同的應用程序的,你定義你的WebMethod你可以重構它到一個實用工具類,並調用它像任何其他方法的文件。 [WebMethod]公開它作爲一項服務,但不會消除你從代碼中使用它的能力。