How can I call a webservice from C# with HTTP POST

If this "webservice" is a simple HTTP GET, you can use WebRequest:

WebRequest request = WebRequest.Create("http://www.temp.com/?param1=x&param2=y");
request.Method="GET";
WebResponse response = request.GetResponse();

From there you can look at response.GetResponseStream for the output. You can hit a POST service the same way.

However, if this is a SOAP webservice, it's not quite that easy. Depending on the security and options of the webservice, sometimes you can take an already formed request and use it as a template - replace the param values and send it (using webrequest), then parse the SOAP response manually... but in that case you're looking at lots of extra work an may as well just use wsdl.exe to generate proxies.


I would explore using ASP.NET MVC for your web service. You can provide parameters via the standard form parameters and return the result as JSON.

[HttpPost]
public ActionResult MyPostAction( string foo, string bar )
{
     ...
     return Json( new { Value = "baz" } );
}

In your client, use the HttpWebRequest

var request = WebRequest.Create( "/controller/mypostaction" );
request.Method = "POST";
var data = string.Format( "foo={0}&bar={1}", foo, bar );
using (var writer = new StreamWriter( request.GetRequestStream() ))
{
    writer.WriteLine( data );
}
var response = request.GetResponse();
var serializer = new DataContractJsonSerializer(typeof(PostActionResult));
var result = serializer.ReadObject( response.GetResponseStream() )
                 as PostActionResult;

where you have

public class PostActionResult
{
     public string Value { get; set; }
}

One other way to call POST method, I used to call POST method in WebAPI.

            WebClient wc = new WebClient();

            string result;
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            result = wc.UploadString("http://localhost:23369/MyController/PostMethodName/Param 1/Param 2","");

            Response.Write(result);