ASP.NET Core Tutorial: HttPClient call WebService in ASP.NET Core in

I. Introduction

In the previous article, I had been told how to call the WebService in ASP.NET Core. But that is by way of a static reference to call, if it is in a production environment, certainly can not be used in this way to call, fortunately Microsoft provides HttpClient, we can HttpClient to call WebService.

Second, create a WebService

We use VS to create a WebService, add a PostTest method, the following method code

the using the System.Web.Services; 

namespace webServiceDemo 
{ 
    ///  <Summary> 
    /// Summary Description WebTest
     ///  </ Summary> 
    [the WebService (the Namespace = " http://tempuri.org/ " )] 
    [the WebServiceBinding ( conformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem ( false )]
     // To call this allows the use of ASP.NET AJAX Web service from a script, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService] 
    public  class WebTest: the System.Web.Services.WebService 
    { 

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

        [the WebMethod] 
        public  String PostTest ( String para) 
        { 
            return $ " return parameter para} { " ; 
        } 
    } 
}

After the creation is complete, we publish WebService, and deployed to IIS above. Guarantee normal browsing in IIS.

Third, the use HttpClient to invoke WebService

We use VS to create an ASP.NET Core WebAPI project, as is the use HttpClient, first performed in ConfigureServices injection method

public void ConfigureServices(IServiceCollection services)
{
    // 注入HttpClient
    services.AddHttpClient();
    services.AddControllers();
}

Then add a controller named WebServiceTest, add a controller inside the Get method, in which calls to take the WebService Get method, the following controller code

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml;

namespace HttpClientDemo.Controllers
{
    [Route("api/WebServiceTest")]
    [ApiController]
    public class WebServiceTestController : ControllerBase
    {
        readonly IHttpClientFactory _httpClientFactory;

        /// <summary>
        /// 通过构造函数实现注入
        /// </ Summary> 
        ///  <param name = "httpClientFactory"> </ param> 
        public WebServiceTestController (IHttpClientFactory httpClientFactory) 
        { 
            _httpClientFactory = httpClientFactory; 
        } 

        [HttpGet] 
        public  the async the Task < String > the Get () 
        { 
            String strResult = "" ;
             the try 
            { 
                // URL address format: WebService method name address +     
                 // the WebService address: HTTP: // localhost : 5010 / WebTest.asmx
                 // method name: PostTest
                string url = "http://localhost:5010/WebTest.asmx/PostTest";
                // 参数
                Dictionary<string, string> dicParam = new Dictionary<string, string>();
                dicParam.Add("para", "1");
                // 将参数转化为HttpContent
                HttpContent content = new FormUrlEncodedContent(dicParam);
                strResult = await PostHelper(url, content);
            }
            catch (Exception ex)
            {
                strResult = ex.Message;
            }

            return strResult;
        }

        /// <summary>
        /// 封装使用HttpClient调用WebService
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="content">参数</param>
        /// <returns></returns>
        private async Task<string> PostHelper(string url, HttpContent content)
        {
            var result = string.Empty;
            try
            {
                using (var client = _httpClientFactory.CreateClient())
                using (var response = await client.PostAsync(url, content))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        result = await response.Content.ReadAsStringAsync();
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(result);
                        result = doc.InnerText;
                    }
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
    }
}

Then start debugging, view the output

Commissioning of the returned results can be seen in the results page to see the return of 

This completes the Calling WebService. Production environment, we can write the URL address in the configuration file inside, and then inside the program to read the contents of the configuration file, so that you can achieve a dynamic call WebService. We transform the above method, the configuration file inside the URL in appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  // url地址
  "url": "http://localhost:5010/WebTest.asmx/PostTest"
}

Get method modified controller

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml;

namespace HttpClientDemo.Controllers
{
    [Route("api/WebServiceTest")]
    [ApiController]
    public class WebServiceTestController : ControllerBase
    {
        readonly IHttpClientFactory _httpClientFactory;
        readonly IConfiguration _configuration;

        /// <summary>
        /// 通过构造函数实现注入
        /// </summary>
        /// <param name="httpClientFactory"></param>
        public WebServiceTestController(IHttpClientFactory httpClientFactory, IConfiguration configuration)
        {
            _httpClientFactory = httpClientFactory;
            _configuration = configuration;
        }

        [HttpGet]
        public async Task<string> Get()
        {
            string strResult = "";
            try
            { 
                // URL address format: WebService method name address +     
                 // the WebService Address: HTTP: // localhost : 5010 / WebTest.asmx
                 // Method Name: PostTest
                 // the URL address reading configuration file which settings
                 // String URL = " HTTP: // localhost : 5010 / WebTest.asmx / PostTest"; 
                String URL = _configuration [ " URL " ];
                 // parameters of 
                the Dictionary < String , String > = dicParam new new the Dictionary < String , String >(); 
                DicParam.Add ( " para " , " . 1 " );
                 // parameter into HttpContent 
                HttpContent Content = new new FormUrlEncodedContent (dicParam); 
                strResult = the await PostHelper (URL, Content); 
            } 
            the catch (Exception EX) 
            { 
                strResult = ex.Message; 
            } 

            return strResult; 
        } 

        ///  <Summary> 
        /// package HttpClient call using the WebService
         /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="content">参数</param>
        /// <returns></returns>
        private async Task<string> PostHelper(string url, HttpContent content)
        {
            var result = string.Empty;
            try
            {
                using (var client = _httpClientFactory.CreateClient())
                using (var response = await client.PostAsync(url, content))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        result = await response.Content.ReadAsStringAsync();
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(result);
                        result = doc.InnerText;
                    }
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
    }
}

This allows the dynamic call WebService. 

Guess you like

Origin www.cnblogs.com/dotnet261010/p/12631911.html