Web Service without adding a reference?

I have 3 web services added to service references in a class library.(This is a sample project for an API use) I need to move these into my project but i cannot add the service references because of the security issues(By security issues i mean the service only responds to one ip address and that is the ip address of our customer’s server.) Is there a way to generate a class like using “Ildasm.exe” for that particaluar web service?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use this class. I didn’t remember where i found the basic code, i added some methods and convert to class before.

public class WebService
{
    public string Url { get; set; }
    public string MethodName { get; set; }
    public Dictionary<string, string> Params = new Dictionary<string, string>();
    public XDocument ResultXML;
    public string ResultString;

    public WebService()
    {

    }

    public WebService(string url, string methodName)
    {
        Url = url;
        MethodName = methodName;
    }

    /// <summary>
    /// Invokes service
    /// </summary>
    public void Invoke()
    {
        Invoke(true);
    }

    /// <summary>
    /// Invokes service
    /// </summary>
    /// <param name="encode">Added parameters will encode? (default: true)</param>
    public void Invoke(bool encode)
    {
        string soapStr =
            @"<?xml version=""1.0"" encoding=""utf-8""?>
            <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
               xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
               xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
              <soap:Body>
                <{0} xmlns=""http://tempuri.org/"">
                  {1}
                </{0}>
              </soap:Body>
            </soap:Envelope>";

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
        req.Headers.Add("SOAPAction", ""http://tempuri.org/" + MethodName + """);
        req.ContentType = "text/xml;charset="utf-8"";
        req.Accept = "text/xml";
        req.Method = "POST";

        using (Stream stm = req.GetRequestStream())
        {
            string postValues = "";
            foreach (var param in Params)
            {
                if (encode)
                    postValues += string.Format("<{0}>{1}</{0}>", HttpUtility.UrlEncode(param.Key), HttpUtility.UrlEncode(param.Value));
                else
                    postValues += string.Format("<{0}>{1}</{0}>", param.Key, param.Value);
            }

            soapStr = string.Format(soapStr, MethodName, postValues);
            using (StreamWriter stmw = new StreamWriter(stm))
            {
                stmw.Write(soapStr);
            }
        }

        using (StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream()))
        {
            string result = responseReader.ReadToEnd();
            ResultXML = XDocument.Parse(result);
            ResultString = result;
        }
    }
}

And you can use like this

WebService ws = new WebService("service_url", "method_name");
ws.Params.Add("param1", "value_1");
ws.Params.Add("param2", "value_2");
ws.Invoke();
// you can get result ws.ResultXML or ws.ResultString

Method 2

You don’t need to add web service reference to play with web service code: You can manually generate class to play with e.g.:

wsdl.exe /out:d:/Proxy.cs /order http://localhost:2178/Services.asmx

And then you can add this file manually to your project.

Method 3

Here’s an example of how to call a “GET” web service from your C# code:

public string CallWebService(string URL)
{
    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(URL);
    objRequest.Method = "GET";
    objRequest.KeepAlive = false;

    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
    string result = "";
    using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
    {
        result = sr.ReadToEnd();
        sr.Close();
    }
    return result;
}

Simply pass it a URL, and it’ll return a string containing the response. From there, you can call the JSON.Net “DeserializeObject” function to turn the string into something useful:

string JSONresponse = CallWebService("http://www.inorthwind.com/Service1.svc/getAllCustomers");

List<Customer> customers = JsonConvert.DeserializeObject<List<Customer>>(JSONresponse);

Hope this helps.

Method 4

You can dynamically change the url of a service reference:

var service = new MyService.MyWSSoapClient();
service.Endpoint.Address = new System.ServiceModel.EndpointAddress("http://localhost:8080/");

Method 5

Yes if you dont want to Add reference wsdl.exe /out:d:/Proxy.cs /order would be the alternative

Method 6

If you using wcf service with json, you can implement sample post method i used in my one of projects. You need newtonsoft json package;

    public static ResponseCL PostPurchOrder(PurchaseOrder order)
    {
        ResponseCL res = new ResponseCL();
        string methodUrl = $"{_main.ws_url}/AddPurchaseOrder";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(methodUrl);
        httpWebRequest.ContentType = "application/json;";
        //if use basic auth//
        //string username = "user";
        //string password = "1234";
        //string encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
        //httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
        httpWebRequest.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(JsonConvert.SerializeObject(order));
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            res = JsonConvert.DeserializeObject<ResponseCL>(result);
        }
        return res;
    }

Another way using Microsoft.AspNet.WebApi.Client package like this;

    public static ResponseCL PostPurchOrder2(PurchaseOrder order)
    {
        ResponseCL res = new ResponseCL();
        using (var client = new HttpClient())
        {
            string methodUrl = $"{_main.ws_url}/AddPurchaseOrder";
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = client.PostAsJsonAsync(methodUrl, order);
            response.Wait();
            if (response.Result.IsSuccessStatusCode)
            {
                string responseString = response.Result.Content.ReadAsStringAsync().Result;
                res = JsonConvert.DeserializeObject<ResponseCL>(responseString);
            }
        }
        return res;
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x