4

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;
}
2
  • Right click on project in solution explorer, Add service reference , specify the URL of your web service. That will create a proxy class in your project, use that to call your method. Commented Oct 25, 2013 at 18:47
  • habib it is a method in the asp.net project Commented Oct 25, 2013 at 18:49

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot it really worked.. but what if we do not know the parameter is "value"?
As far as I know, the name of the parameter must match, what scenario would you not know the parameter name?
no i dont know that is the problem i even dont know the method name. i was jus given the "somewebsite.com/somthing.aspx"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.