C# .Net6 specifies WSDL, generates Webservice, and calls the interface service

C# .Net6 specifies WSDL and calls this interface service.

  • IDE: Microsoft Visual Studio Community 2022 (64-bit)
  • Platform: .Net6
  • Protocol: Soap protocol Xml format

Function

  • A front-end computer program needs to be developed to interact with the hardware program.
  • The known conditions are: the embedded colleague provides another agreed *.wsdl file as the Webservice interface protocol for communication between the two parties. The other party is the server and the front-end machine is the client.

Implementation method 1

  • Using BasicHttpBinding

Generate WEB services through WSDL files

Note that here, the prompt steps for my VS2022 are slightly different from the steps found online. The following steps are the steps for my VS2022:

  1. First, open the .NET 6 project in VS2022 or create a new .NET 6 project.

  2. In Solution Explorer, right-click the project name and select Add -> Service Reference.

  3. In the “Add Service Reference” window, there are three options,

    • OpenAPI,
    • gRPC
    • WCF Web Service

    Select WCF Web Service here and enter the window “Add new WCF Web Service reference

  4. Click the Browse button and select your WSDL file from the file system.

  5. After selecting the WSDL file, the configuration referenced by the service will be displayed at the bottom of the window. Here you can modify the namespace to the name you want in the input box below, click Next, and in the new window, you can specify data type options font>, the default does not need to be changed, click “Finish“.

  6. At this time, VS2022 will generate the code of the Web service based on your WSDL file, that is, the proxy class of the original Webservice service.

  7. There is also a method to generate a Webservice service proxy class:

    • Using the wsdl.exe tool
    • The command is: wsdl /language:c# /n:Fu /out:d:/MyService.cs C:\Users\Administrator\Desktop\MyService.wsdl)
      • “d:/MyService.cs” is the output directory
      • “C:\Users\Administrator\Desktop\MyService.wsdl” is the location of the source wsdl file
    • For specific usage, you can use search engines to query, and I won’t go into details here.
Method of calling the WebService
 public static async Task TestCallWs()
        {
            mydemo.TestMyClient serv = null;
            try
            {
                var binding = new BasicHttpBinding();
                var endpoint = new EndpointAddress(UrlString); // url address
                serv = new mydemo.TestMyClient(binding, endpoint);
                var result = await serv.invokeAsync(ParamsString); // String parameters in xml format
                Console.WriteLine("Return interface data:\
 " + result);
                
            }
            catch(HttpRequestException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                if (serv != null)
                {
                    serv.Close();
                }
            }
        }

Implementation method 2

Use HttpClient

Simple encapsulation

- Definition: WsClient
 public class WsClient
    {
        // interface address
        private string mUrl = string.Empty;
        //Request parameters
        private string mParam = string.Empty;

         namespace namespace
        //private string ns = "http://XXX:xx/xx/xx"; //TODO fill in the namespace name you need
        
         Request method name
        //private string funName = string.Empty;

        publicWsClient()
        {
            throw new NotImplementedException();
        }

        public WsClient(string url)
        {
            this.mUrl = url;
        }

        public async Task<string> Request(string param)
        {
            if (string.IsNullOrEmpty(mUrl))
            {
                return "The interface address is empty!";
            }

            if (!mUrl.Contains("http"))
            {
                return "Illegal interface address!";
            }

            if (string.IsNullOrEmpty(param))
            {
                return "The request parameters are empty!";
            }

            this.mParam = param;

            try
            {
                HttpClient httpClient = new();

                //soap parameters
                string payload =
                    @"<?xml version=""1.0""?>
                        <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                            <soap:Body>
                            <invoke xmlns=""http://xxxxx.yyyyyyyy.com"">
                                <xmlData>" + mParam +
                           @"</xmlData>
                            </invoke>
                            </soap:Body>
                        </soap:Envelope>";

                //Send SOAP request and get response
                HttpResponseMessage response = await httpClient.PostAsync(mUrl, new StringContent(payload, Encoding.UTF8, "text/xml"));

                // Parse SOAP response
                string respStr = await response.Content.ReadAsStringAsync();
                return respStr;
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("WsClient -> Request() exception: {0} ", e.Message);
            }

            return "";
        }
    }

Calling method:

string result = await new WsClient(wsUrl).Request(xmlData);

wsUrl: is your Webservice interface address;
xmlData: It is the data parameter in xml format agreed in the protocol you assembled. The example is as follows:
result: is the request interface, and the returned data is also in xml format.

<?xml version=""1.0"" encoding=""UTF-8""?>
<Request>
    <Name>
        QueryUsers
    </Name>
    <Info>
        <ID>21202012211211</ID>
    </Info>
</Request>

Complete

  • After a simple experiment, I feel that the performance of Method 2 is slightly better than the implementation of Method 1. I am currently using method 2.
syntaxbug.com © 2021 All Rights Reserved.