一、前言

在以前的一篇文章中,曾经讲述过如何在ASP.NET Core中调用WebService。但是那种方式是通过静态引用的方式去调用的,如果是在生产环境中,肯定不能使用这种方式去调用,幸运的是微软提供了HttpClient,我们可以通过HttpClient去调用WebService。

二、创建WebService

我们使用VS创建一个WebService,增加一个PostTest方法,方法代码如下

using System.Web.Services;

namespace WebServiceDemo
{
/// <summary>
/// WebTest 的摘要说明
/// </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 WebTest : System.Web.Services.WebService
{ [WebMethod]
public string HelloWorld()
{
return "Hello World";
} [WebMethod]
public string PostTest(string para)
{
return $"返回参数{para}";
}
}
}

创建完成以后,我们发布WebService,并部署到IIS上面。保证可以在IIS正常浏览。

三、使用HttpClient调用WebService

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

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

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

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<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;
}
}
}

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

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

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

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

修改控制器的Get方法

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<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;
}
}
}

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

ASP.NET Core教程:在ASP.NET Core中使用HttPClient调用WebService的更多相关文章

  1. 【ASP.NET实战教程】ASP.NET实战教程大集合,各种项目实战集合

    [ASP.NET实战教程]ASP.NET实战教程大集合,各种项目实战集合,希望大家可以好好学习教程中,有的比较老了,但是一直很经典!!!!论坛中很多小伙伴说.net没有实战教程学习,所以小编连夜搜集整 ...

  2. ASP.NET Core教程:ASP.NET Core程序部署到Linux

    一.前言 这篇文章我们将讲解如何将ASP.NET Core 程序部署到Linux.这里我们使用的是虚拟机里面安装的Centos7.这里的ASP.NET Core程序,以上篇文章中发布的框架依赖文件为例 ...

  3. ASP.NET Core教程:ASP.NET Core 程序部署到Windows系统

    一.创建项目 本篇文章介绍如何将一个ASP.NET Core Web程序部署到Windows系统上.这里以ASP.NET Core WebApi为例进行讲解.首先创建一个ASP.NET Core We ...

  4. ASP.NET Core教程:ASP.NET Core中使用Redis缓存

    参考网址:https://www.cnblogs.com/dotnet261010/p/12033624.html 一.前言 我们这里以StackExchange.Redis为例,讲解如何在ASP.N ...

  5. ASP.NET Core教程:ASP.NET Core使用AutoMapper

    一.前言 在实际的项目开发过程中,我们使用各种ORM框架可以使我们快捷的获取到数据,并且可以将获取到的数据绑定到对应的List<T>中,然后页面或者接口直接显示List<T>中 ...

  6. 通过HttpClient 调用ASP.NET Web API

    在前面两篇文章中我们介绍了ASP.NET Web API的基本知识和原理,并且通过简单的实例了解了它的基本(CRUD)操作.我们是通过JQuery和Ajax对Web API进行数据操作.这一篇我们来介 ...

  7. Working with Data » 使用Visual Studio开发ASP.NET Core MVC and Entity Framework Core初学者教程

    原文地址:https://docs.asp.net/en/latest/data/ef-mvc/intro.html The Contoso University sample web applica ...

  8. 003.ASP.NET Core tutorials--【Asp.net core 教程】

    ASP.NET Core tutorials Asp.net core 教程 2016-10-14 1 分钟阅读时长 本文内容 1.Building web applications 构建web应用 ...

  9. ASP.NET Core教程【二】从保存数据看特有属性与服务端验证

    前文索引: 在layout.cshtml文件中,我们可以看到如下代码: <a asp-page="/Index" class="navbar-brand" ...

随机推荐

  1. Docker以过时,看Containerd怎样一统天下

    Docker作为非常流行的容器技术,之前经常有文章说它被K8S弃用了,取而代之的是另一种容器技术containerd!其实containerd只是从Docker中分离出来的底层容器运行时,使用起来和D ...

  2. HCNA Routing&Switching之动态路由协议OSPF建立邻居的条件

    前文我们了解了OSPF的router id.数据包结构.类型.不同类型的数据包作用以及OSPF状态机制,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/15027 ...

  3. C语言:按行读TXT文件

    //搂行读取TXT #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_L ...

  4. GraphQL 概念入门

    GraphQL 概念入门 Restful is Great! But GraphQL is Better. -- My Humble Opinion. GraphQL will do to REST ...

  5. [HAOI2012]外星人 题解

    人类智慧题. 首先,只有 \(\varphi(1)=\varphi(2)=1\).再考虑题目中给的提示: \[\varphi\left(\prod_{i = 1}^m p_i^{q_i}\right) ...

  6. [考试总结]noip模拟7

    为啥博客园 \(\LaTeX\) 老挂???! \(\huge{\text{菜}}\) 刚开始写 \(T1\) 的时候,在看到后缀前缀之后,直接想到 \(AC\) 自动机,在画了半个 \(trie\) ...

  7. CSS样式实现表头和列固定

    效果图:第一行和第一列固定       <!DOCTYPE html> <html lang="zh"> <head> <meta cha ...

  8. 迈达斯midas Gen 2019 2.1 中文汉化安装教程

    midas Gen 2019 v2.1 for win是一款关于结构设计有限元分享的工具,分为建筑领域.桥梁领域.岩土领域.仿真领域四个大类.具有人性化的操作界面,且采用了优秀的的计算机显示技术,是建 ...

  9. document.all("div).style.display = "none"与 等于""的区别

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. WIN XP SP2系统经常性死机问题解决历程

    如题: 1.初始时,XP还能进入系统,等系统3分钟左右,鼠标熄灭,键盘无反应,查看资源管理器CPU 100%,内存占用不高. 2.现象初步分析: a.怀疑是病毒占用CPU 100%,于是下载360安全 ...