ASP.NET Core使用HttpClient調(diào)用WebService
一、創(chuàng)建WebService
我們使用VS創(chuàng)建一個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 從腳本中調(diào)用此 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 $"返回參數(shù){para}";
}
}
}創(chuàng)建完成以后,我們發(fā)布WebService,并部署到IIS上面。保證可以在IIS正常瀏覽。
二、使用HttpClient調(diào)用WebService
我們使用VS創(chuàng)建一個ASP.NET Core WebAPI項目,由于是使用HttpClient,首先在ConfigureServices方法中進行注入
public void ConfigureServices(IServiceCollection services)
{
// 注入HttpClient
services.AddHttpClient();
services.AddControllers();
}然后添加一個名為WebServiceTest的控制器,在控制器里面添加一個Get方法,在Get方法里面取調(diào)用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>
/// 通過構(gòu)造函數(shù)實現(xiàn)注入
/// </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";
// 參數(shù)
Dictionary<string, string> dicParam = new Dictionary<string, string>();
dicParam.Add("para", "1");
// 將參數(shù)轉(zhuǎn)化為HttpContent
HttpContent content = new FormUrlEncodedContent(dicParam);
strResult = await PostHelper(url, content);
}
catch (Exception ex)
{
strResult = ex.Message;
}
return strResult;
}
/// <summary>
/// 封裝使用HttpClient調(diào)用WebService
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="content">參數(shù)</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;
}
}
}然后啟動調(diào)試,查看輸出結(jié)果

調(diào)試的時候可以看到返回結(jié)果,在看看頁面返回的結(jié)果

這樣就完成了WebService的調(diào)用。生產(chǎn)環(huán)境中我們可以URL地址寫在配置文件里面,然后程序里面去讀取配置文件內(nèi)容,這樣就可以實現(xiàn)動態(tài)調(diào)用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>
/// 通過構(gòu)造函數(shù)實現(xiàn)注入
/// </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
// 讀取配置文件里面設(shè)置的URL地址
//string url = "http://localhost:5010/WebTest.asmx/PostTest";
string url = _configuration["url"];
// 參數(shù)
Dictionary<string, string> dicParam = new Dictionary<string, string>();
dicParam.Add("para", "1");
// 將參數(shù)轉(zhuǎn)化為HttpContent
HttpContent content = new FormUrlEncodedContent(dicParam);
strResult = await PostHelper(url, content);
}
catch (Exception ex)
{
strResult = ex.Message;
}
return strResult;
}
/// <summary>
/// 封裝使用HttpClient調(diào)用WebService
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="content">參數(shù)</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;
}
}
}這樣就可以動態(tài)調(diào)用WebService了。
到此這篇關(guān)于ASP.NET Core使用HttpClient調(diào)用WebService的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Asp.Net中的Action和Func委托實現(xiàn)
這篇文章主要介紹了Asp.Net中的Action和Func委托的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12
使用.Net實現(xiàn)多線程經(jīng)驗總結(jié)
這篇文章主要介紹了使用.Net實現(xiàn)多線程經(jīng)驗總結(jié),需要的朋友可以參考下2014-12-12
asp.net實現(xiàn)根據(jù)城市獲取天氣預報的方法
這篇文章主要介紹了asp.net實現(xiàn)根據(jù)城市獲取天氣預報的方法,涉及asp.net調(diào)用新浪接口獲取天氣預報信息的實現(xiàn)技巧,非常簡單實用,需要的朋友可以參考下2015-12-12
Asp.net core WebApi 使用Swagger生成幫助頁實例
本篇文章主要介紹了Asp.net core WebApi 使用Swagger生成幫助頁實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04
.net WINFORM的GDI雙緩沖的實現(xiàn)方法
下面小編就為大家分享一篇.net WINFORM的GDI雙緩沖的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12

