在ASP.NET Core調用WebService


一、前言

現實生產中,有一些比較老的系統對外提供的接口都是WebService形式的,如果是使用.NET Framework創建的項目調用WebService非常方便,網上有很多代碼示例,這里不在講解,下面我們講解如何在ASP.NET Core項目里面調用WebService。首先我們需要創建一個WebService項目和一個ASP.NET Core WebApi項目。創建的WebService代碼如下:

using System.Web.Services;

namespace CoreCallWebServiceTest
{
    /// <summary>
    /// CoreTest 的摘要說明
    /// </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 CoreTest : System.Web.Services.WebService
    {

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        [WebMethod]
        public string TestMethod(string para)
        {
            return $"輸入參數:{para}";
        }
    }
}

里面分別有一個無參和有參的方法。我們在ASP.NET Core WebApi項目里面分別調用這兩個方法並輸出。

二、引用WebService

首先我們在創建好的ASP.NET Core WebApi項目里面添加WebService的引用。

1、在依賴項上面右鍵,選擇“添加連接的服務”,如圖所示:

 2、選擇“Microsoft WCF Web Service Referenct Provider”,如圖所示:

 3、添加服務引用。如圖所示:

配置完以后,點擊“下一步”,去掉重新使用引用的程序集中的類型簽名的復選框。如果不去掉復選框,生成的時候可能會報錯。

直接點擊“完成”按鈕即可。慢慢等待配置完成:

配置完成界面如圖所示:

這樣就添加完了,下面開始在代碼里面調用提供的WebService里面的方法。

三、在代碼中調用WebService

我們添加一個名為Test的控制器,里面有一個Get方法,返回WebService里面兩個方法的返回值,代碼如下:

using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestWebService;

namespace AspNetCoreDemo.Controllers
{
    [Route("api/Test")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            //創建 HTTP 綁定對象
            var binding = new BasicHttpBinding();
            //根據 WebService 的 URL 構建終端點對象,參數是提供的WebService地址
            var endpoint = new EndpointAddress(@"http://localhost:37907/CoreTest.asmx");
            //創建調用接口的工廠,注意這里泛型只能傳入接口 泛型接口里面的參數是WebService里面定義的類名+Soap
            var factory = new ChannelFactory<CoreTestSoap>(binding, endpoint);
            //從工廠獲取具體的調用實例
            var callClient = factory.CreateChannel();
            //調用具體的方法,這里是 HelloWorldAsync 方法
            Task<HelloWorldResponse> responseTask = callClient.HelloWorldAsync(new HelloWorldRequest());
            //獲取結果
            HelloWorldResponse response = responseTask.Result;
            // 獲取HelloWorld方法的返回值
            string result1 = response.Body.HelloWorldResult;

            // 調用TestMethod方法,不傳遞參數
            Task<TestMethodResponse> testResponse = callClient.TestMethodAsync(new TestMethodRequest());
            // 獲取
            string result2 = testResponse.Result.Body.TestMethodResult;

            // 調用TestMethod方法,並傳遞參數
            TestMethodRequestBody body = new TestMethodRequestBody("測試TestMethod方法");
            Task<TestMethodResponse> testResponsePara = callClient.TestMethodAsync(new TestMethodRequest(body));
            // 獲取
            string result3 = testResponse.Result.Body.TestMethodResult;

            return $"HelloWorld方法返回值:{result1},TestMethod方法不傳遞參數返回值:{result2},TestMethod方法傳遞參數的返回值:{result3}";
        }
    }
}

我們在WebService里面定義的TestMethod方法有一個string類型的參數,調用的時候有兩個重載函數,一個無參,一個有參,看一下自動生成的Reference.cs類里面的代碼:

發現TestMethodRequestBody有兩個構造函數:一個無參,一個有參。我們在瀏覽器里面調用Get方法,程序輸出結果:

除了上面的代碼,也可以使用下面的代碼進行調用:

using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestWebService;

namespace AspNetCoreDemo.Controllers
{
    [Route("api/Test")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            #region 調用方法1
            ////創建 HTTP 綁定對象
            //var binding = new BasicHttpBinding();
            ////根據 WebService 的 URL 構建終端點對象,參數是提供的WebService地址
            //var endpoint = new EndpointAddress(@"http://localhost:37907/CoreTest.asmx");
            ////創建調用接口的工廠,注意這里泛型只能傳入接口 泛型接口里面的參數是WebService里面定義的類名+Soap
            //var factory = new ChannelFactory<CoreTestSoap>(binding, endpoint);
            ////從工廠獲取具體的調用實例
            //var callClient = factory.CreateChannel();
            ////調用具體的方法,這里是 HelloWorldAsync 方法
            //Task<HelloWorldResponse> responseTask = callClient.HelloWorldAsync(new HelloWorldRequest());
            ////獲取結果
            //HelloWorldResponse response = responseTask.Result;
            //// 獲取HelloWorld方法的返回值
            //string result1 = response.Body.HelloWorldResult;

            //// 調用TestMethod方法,不傳遞參數
            //Task<TestMethodResponse> testResponse = callClient.TestMethodAsync(new TestMethodRequest());
            //// 獲取
            //string result2 = testResponse.Result.Body.TestMethodResult;

            //// 調用TestMethod方法,並傳遞參數
            //TestMethodRequestBody body = new TestMethodRequestBody("測試TestMethod方法");
            //Task<TestMethodResponse> testResponsePara = callClient.TestMethodAsync(new TestMethodRequest(body));
            //// 獲取
            //string result3 = testResponsePara.Result.Body.TestMethodResult; 
            #endregion


            #region 調用方法2
            BasicHttpBinding binding = new BasicHttpBinding();

            EndpointAddress address = new EndpointAddress("http://localhost:37907/CoreTest.asmx");

            CoreTestSoapClient client = new CoreTestSoapClient(binding, address);

            Task<HelloWorldResponse> responseTask = client.HelloWorldAsync();
            HelloWorldResponse response = responseTask.Result;
            // 獲取HelloWorld方法的返回值
            string result1 = response.Body.HelloWorldResult;

            // 調用TestMethod方法,這時必須傳入參數
            Task<TestMethodResponse> testResponseTask = client.TestMethodAsync("測試TestMethod方法");
            // 獲取TestMethod方法的返回值
            string result2 = testResponseTask.Result.Body.TestMethodResult;
            #endregion
            return $"HelloWorld方法返回值:{result1},TestMethod方法返回值:{result2}";
        }
    }
}

在這種方式中,調用有參的方法必須要傳遞參數。

程序運行結果:

如果以后WebService有更新,只需要更新添加的服務引用即可,如圖所示:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM