views:

59

answers:

2

I want to write a c# class that would create a connection to a webservice running to www.temp.com, send 2 string params to the method DoSomething and get the string result. I don't want to use wsdl. Since I know the params of the webservice, I just want to make a simple call.

I guess there should be an easy and simple way to do that in .Net 2, but I couldn't find any example...

+1  A: 

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.

Philip Rieck
This looks like what I need. How can I add the method name (DoSomething) to this call?
Stavros
OK, after some playing around, I managed to find out the extra stuff needed to make it with Post. Thanks
Stavros
+1  A: 

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; }
}
tvanfosson
Thanks for the information, but I have already implemented it without Json. Next time I will experiement with that.
Stavros