在windows项目中调用asp.net webmethod

时间:2013-10-25 18:44:29

标签: c# asp.net web-services webmethod

如何从Windows应用程序中调用ASP.NET中的WebMethod

我尝试过使用web request post方法,但它返回了ASP.NET页面的XML。

这是我的网络方法:

[WebMethod()]
public static string Senddata(string value)
{
    return "datareceived" + value;
}

1 个答案:

答案 0 :(得分:5)

试试这个:

var theWebRequest = HttpWebRequest.Create("http://YOURURL/YOURPAGE.aspx/Senddata");
theWebRequest.Method = "POST";
theWebRequest.ContentType = "application/json; charset=utf-8";
theWebRequest.Headers.Add(HttpRequestHeader.Pragma, "no-cache");

using (var writer = theWebRequest.GetRequestStream()) 
{
    string send = null;
    send = "{\"value\":\"test\"}";

    var data = Encoding.ASCII.GetBytes(send);

    writer.Write(data, 0, data.Length);
}

var theWebResponse = (HttpWebResponse)theWebRequest.GetResponse();
var theResponseStream = new StreamReader(theWebResponse.GetResponseStream());

string result = theResponseStream.ReadToEnd();

// Do something with the result
TextBox1.Text = result;

注意:您需要将YOURURLYOURPAGE替换为实际值。