您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“ASP.NET Core如何使用HttpClient調用WebService”,內容詳細,步驟清晰,細節處理妥當,希望這篇“ASP.NET Core如何使用HttpClient調用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正常瀏覽。
我們使用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如何使用HttpClient調用WebService”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。