您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“ASP.NET Core如何使用HttpClient調(diào)用WebService”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“ASP.NET Core如何使用HttpClient調(diào)用WebService”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。
我們使用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 服務(wù),請取消注釋以下行。 // [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正常瀏覽。
我們使用VS創(chuàng)建一個ASP.NET Core WebAPI項(xiàng)目,由于是使用HttpClient,首先在ConfigureServices方法中進(jìn)行注入
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ù)實(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)容,這樣就可以實(shí)現(xiàn)動態(tài)調(diào)用WebService了。我們對上面的方法進(jìn)行改造,在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ù)實(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了。
讀到這里,這篇“ASP.NET Core如何使用HttpClient調(diào)用WebService”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。