ASP.NET Core如何使用HttpClient调用WebService

原文链接:https://www.yisu.com/jc/691937.html

我们使用VS创建一个ASP.NET Core WebAPI项目,由于是使用HttpClient,首先在ConfigureServices方法中进行注入。

1
2
3
4
5
6
public void ConfigureServices(IServiceCollection services)
{
    // 注入HttpClient
    services.AddHttpClient();
    services.AddControllers();
}

  然后添加一个名为WebServiceTest的控制器,在控制器里面添加一个Get方法,在Get方法里面取调用WebService,控制器代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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 async Task<string> Get()
        {
            string strResult = "";
            try
            {
                // url地址格式:WebService地址+方法名称     
                // WebService地址:http://localhost:5010/WebTest.asmx
                // 方法名称:  PostTest
                string url = "http://localhost:5010/WebTest.asmx/PostTest";
                // 参数
                Dictionary<stringstring> dicParam = new Dictionary<stringstring>();
                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;
        }
    }
}

  然后启动调试,查看输出结果

 调试的时候可以看到返回结果,在看看页面返回的结果。

ASP.NET Core如何使用HttpClient调用WebService

这样就完成了WebService的调用。生产环境中我们可以URL地址写在配置文件里面,然后程序里面去读取配置文件内容,这样就可以实现动态调用WebService了。我们对上面的方法进行改造,在appsettings.json文件里面配置URL地址

1
2
3
4
5
6
7
8
9
10
11
12
{
  "Logging": {
    "LogLevel": {
      "Default""Information",
      "Microsoft""Warning",
      "Microsoft.Hosting.Lifetime""Information"
    }
  },
  "AllowedHosts""*",
  // url地址
  "url""http://localhost:5010/WebTest.asmx/PostTest"
}

  修改控制器的Get方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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地址格式:WebService地址+方法名称     
                // WebService地址:http://localhost:5010/WebTest.asmx
                // 方法名称:  PostTest
                // 读取配置文件里面设置的URL地址
                //string url = "http://localhost:5010/WebTest.asmx/PostTest";
                string url = _configuration["url"];
                // 参数
                Dictionary<stringstring> dicParam = new Dictionary<stringstring>();
                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;
        }
    }
}

  这样就可以动态调用WebService了。

posted @   yinghualeihenmei  阅读(75)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示