C# Create WebService interface and connect

Create a WebService project

First install the .NET Framework4.6.2-4.7.1 development tools.
insert image description here
Then there is the new ASP.NET Web应用程序project .
insert image description here
Enter the project name WebServiceDemo
insert image description hereand select empty, and then remove the HTTPS configuration first.
insert image description here
After the project is created, start adding asmxfiles.
insert image description here
After adding, add a named Hellomethod with parameters. The code is as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebServiceDemo
{
    
    
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
    
    

        [WebMethod]
        public string HelloWorld()
        {
    
    
            return "Hello World";
        }
        [WebMethod]
        public string Hello(string name)
        {
    
    
            return "Hello"+name;
        }
    }
}

Then you can start it directly, or publish it to IIS to start it. Here, publish to IIS first, and then create a new console project to connect to the service.
After publishing, add the website in IIS, and bind the port number to 81. Then you can start it.
If you start it directly, the following error may be reported, because the start page is not set.
insert image description here
You can directly enter the address to visit.

http://localhost:81/webservice1.asmx

It is also possible to add files in the IIS Default Documentation webservice1.asmx. You can open it directly when you browse next time.
insert image description here
When the page shown below appears, it means that the service has been successfully deployed.
insert image description here

Connect to the WebService service

Create a new console application.
Then open the webservice address input.

http://localhost:81/webservice1.asmx?wsdl

An xml file will open.
insert image description here
Then right-click the file and save it as, and save the file. And modify the file suffix name wsdl.
insert image description here
Add in VS, add a service reference. Select WCF Web Services.
insert image description here
Here you can actually directly enter the address of the WebService and click Go. When considering that the service to be connected may not be accessible locally, we can click to browse through the wsdl file generated above to generate the corresponding code.
insert image description here
After adding it, as shown in the figure below, the namespace can be modified according to the actual name.
insert image description here
Then click Next, and then click Finish.
insert image description here
After completion, there are two more files here.
insert image description here
The calling method is as follows, directly instantiate the corresponding class, and then call the remote service interface just like calling a normal method.

using ServiceReference1;
using System;
using System.Threading.Tasks;

namespace TestProject
{
    
    
    public class Program
    {
    
    
        static async Task Main(string[] args)
        {
    
    
           await Test();
        }
        public static async Task Test()
        {
    
    
            var reference = new WebService1SoapClient(WebService1SoapClient.EndpointConfiguration.WebService1Soap12);
            var helloWorldResult = await reference.HelloWorldAsync();
            Console.WriteLine(helloWorldResult.Body.HelloWorldResult);
            var str = "张三";
            var helloResult = await reference.HelloAsync(str);
            Console.WriteLine(helloResult.Body.HelloResult);
        }
    }
   
}

The returned result is as follows, which is as natural as calling a local method.
insert image description here

However, there should be some places that need to be modified as needed. In Reference.csthe file, the remote service address is hard-coded. So it needs to be changed to a parameter.

 private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)
        {
    
    
            if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
            {
    
    
                return new System.ServiceModel.EndpointAddress("http://localhost:81/webservice1.asmx");
            }
            if ((endpointConfiguration == EndpointConfiguration.WebService1Soap12))
            {
    
    
                return new System.ServiceModel.EndpointAddress("http://localhost:81/webservice1.asmx");
            }
            throw new System.InvalidOperationException(string.Format("找不到名称为“{0}”的终结点。", endpointConfiguration));
        }

The modification method is also simple. Add a url input parameter.

private static System.ServiceModel.EndpointAddress GetEndpointAddress(string url,EndpointConfiguration endpointConfiguration)
    {
    
    
        if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
        {
    
    
            return new System.ServiceModel.EndpointAddress(url);
        }
        if ((endpointConfiguration == EndpointConfiguration.WebService1Soap12))
        {
    
    
            return new System.ServiceModel.EndpointAddress(url);
        }
        throw new System.InvalidOperationException(string.Format("找不到名称为“{0}”的终结点。", endpointConfiguration));
    }

And the url is added here to refer to this method.

    public WebService1SoapClient(string url, EndpointConfiguration endpointConfiguration) : 
            base(WebService1SoapClient.GetBindingForEndpoint(endpointConfiguration), WebService1SoapClient.GetEndpointAddress(url,endpointConfiguration))
    {
    
    
        this.Endpoint.Name = endpointConfiguration.ToString();
        ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
    }

Just pass in the Url when calling.

var url = "http://localhost:81/webservice1.asmx";
var reference = new WebService1SoapClient(url, WebService1SoapClient.EndpointConfiguration.WebService1Soap12);
var helloWorldResult = await reference.HelloWorldAsync();
Console.WriteLine(helloWorldResult.Body.HelloWorldResult);
var str = "张三";
var helloResult = await reference.HelloAsync(str);
Console.WriteLine(helloResult.Body.HelloResult);

have a wonderful day。

Guess you like

Origin blog.csdn.net/u012869793/article/details/128341811