call asp.net webmethod in windows project

L202 picture L202 · Oct 25, 2013 · Viewed 8.1k times · Source

How do I call this WebMethod in ASP.NET from a Windows application?

I have tried using web request post method, but it is returning the XML of the ASP.NET page.

Here is my web method:

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

Answer

Karl Anderson picture Karl Anderson · Oct 25, 2013

Try this:

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;

Note: You need to replace YOURURL and YOURPAGE with real values.