21

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...

Stavros
  • 5,802
  • 13
  • 32
  • 45

5 Answers5

26

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
  • 32,368
  • 11
  • 87
  • 99
  • 1
    This looks like what I need. How can I add the method name (DoSomething) to this call? – Stavros Oct 10 '10 at 13:30
  • OK, after some playing around, I managed to find out the extra stuff needed to make it with Post. Thanks – Stavros Oct 10 '10 at 14:30
  • if i wan to submit some addition data to the web service whicm am calling then i do i suppose to do that? – Madhav Jul 05 '17 at 09:34
  • Stavros - Perhaps you could post here the "extra stuff needed"? It would be helpful and add value to the answer. – Baruch Atta Feb 13 '19 at 16:16
12

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
  • 524,688
  • 99
  • 697
  • 795
  • Thanks for the information, but I have already implemented it without Json. Next time I will experiement with that. – Stavros Oct 12 '10 at 11:21
  • DataContractJsonSerializer is not recognized by Visual Studio, maybe need a using? – Windgate Jul 15 '20 at 15:38
4

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);
Prateek Gupta
  • 880
  • 1
  • 10
  • 21
1

You can return List object use Newtonsoft.Json:

WebClient wc = new WebClient();
  string result;
  wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
  var data = string.Format("Value1={0}&Value2={1}&Value3={2}", "param1", "param2", "param3");
  result = wc.UploadString("http:your_services", data);
  var ser = new JavaScriptSerializer();
  var people = ser.Deserialize<object_your[]>(result);
Tran Anh Hien
  • 687
  • 8
  • 11
1

This a static method to call any service without credentials

    /// <summary>
    ///     Connect to service without credentials
    /// </summary>
    /// <param name="url">string url</param>
    /// <param name="requestType">type of request</param>
    /// <param name="objectResult">expected success object result</param>
    /// <param name="objectErrorResult">expected error object result</param>
    /// <param name="objectErrorResultDescription">expected error object description</param>
    /// <param name="body">request body</param>
    /// <param name="bodyType">type of body</param>
    /// <param name="parameters">parameters of request</param>
    /// <returns></returns>
    public static object ConnectToService(string url, string model, RequestType requestType, string objectResult, string objectErrorResult,
                                                      string objectErrorResultDescription, string body = null, string bodyType = null,
                                                      string parameters = null)
    {
        try
        {
            HttpClient client = new HttpClient();
            string tokenEndpoint = url;
            StringContent stringContent;
            string result = string.Empty;

            switch (requestType)
            {
                case RequestType.Get:
                    {
                        var returnRequest = client.GetAsync(tokenEndpoint).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Post:
                    {
                        stringContent = new StringContent(body, Encoding.UTF8, bodyType);

                        var returnRequest = client.PostAsync(tokenEndpoint, stringContent).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Put:
                    {
                        stringContent = new StringContent(body, Encoding.UTF8, bodyType);

                        var returnRequest = client.PutAsync(tokenEndpoint, stringContent).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Delete:
                    {
                        var returnRequest = client.DeleteAsync(tokenEndpoint).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                default:
                    break;
            }

            JObject jobject = !string.IsNullOrEmpty(result) ? JObject.Parse(result) : null;
            var obj = jobject != null ? (jobject[objectResult]?.ToList()?.Count > 0 ? jobject[objectResult]?.ToList() : null) : null;

            return (obj == null && jobject?.ToString() == null && jobject[objectResult]?.ToString() == null) ? throw new Exception(($"{jobject[objectErrorResult]?.ToString()} - {jobject[objectErrorResultDescription]?.ToString()}") ?? (new { Error = new { Code = 400, Message = $"{model} - Requisição inválida." } }).ToString()) : (obj ?? (object)jobject[objectResult]?.ToString()) == null ? jobject : (obj ?? (object)jobject[objectResult]?.ToString());
        }
        catch (NullReferenceException)
        {
            return null;
        }
        catch (Exception e)
        {
            throw new Exception($"{model} - Requisição inválida. Detalhes: {e.Message ?? e.InnerException.Message}");
        }
    }

This a static method to call any service with credentials

    /// <summary>
    ///     Connect to service with credentials
    /// </summary>
    /// <param name="url">string url</param>
    /// <param name="requestType">type of request</param>
    /// <param name="handler">credentials</param>
    /// <param name="objectResult">expected success object result</param>
    /// <param name="objectErrorResult">expected error object result</param>
    /// <param name="objectErrorResultDescription">expected error object description</param>
    /// <param name="body">request body</param>
    /// <param name="bodyType">type of body</param>
    /// <param name="parameters">parameters of request</param>
    /// <returns></returns>
    public static object ConnectToService(string url, string model, RequestType requestType, HttpClientHandler handler, string objectResult, string objectErrorResult,
                                                      string objectErrorResultDescription, string body = null, string bodyType = null,
                                                      string parameters = null)
    {
        try
        {
            HttpClient client = new HttpClient(handler);
            string tokenEndpoint = url;
            StringContent stringContent;
            string result = string.Empty;

            switch (requestType)
            {
                case RequestType.Get:
                    {
                        var returnRequest = client.GetAsync(tokenEndpoint).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Post:
                    {
                        stringContent = new StringContent(body, Encoding.UTF8, bodyType);

                        var returnRequest = client.PostAsync(tokenEndpoint, stringContent).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Put:
                    {
                        stringContent = new StringContent(body, Encoding.UTF8, bodyType);

                        var returnRequest = client.PutAsync(tokenEndpoint, stringContent).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                case RequestType.Delete:
                    {
                        var returnRequest = client.DeleteAsync(tokenEndpoint).Result;
                        result = returnRequest.Content.ReadAsStringAsync().Result;

                        break;
                    }
                default:
                    break;
            }

            JObject jobject = !string.IsNullOrEmpty(result) ? JObject.Parse(result) : null;
            var obj = jobject != null ? (jobject[objectResult]?.ToList()?.Count > 0 ? jobject[objectResult]?.ToList() : null) : null;

            return (obj == null && jobject?.ToString() == null && jobject[objectResult]?.ToString() == null) ? throw new Exception(($"{jobject[objectErrorResult]?.ToString()} - {jobject[objectErrorResultDescription]?.ToString()}") ?? (new { Error = new { Code = 400, Message = $"{model} - Requisição inválida." } }).ToString()) : (obj ?? (object)jobject[objectResult]?.ToString()) == null ? jobject : (obj ?? (object)jobject[objectResult]?.ToString());
        }
        catch (NullReferenceException)
        {
            return null;
        }
        catch (Exception e)
        {
            throw new Exception($"{model} - Invalid request. {e.Message.Split(',')[0] ?? e.InnerException.Message.Split(',')[0]}");
        }
    }
Tasso Mello
  • 347
  • 2
  • 5