ASP.NET Core使用HttpClient調用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 從腳本中調用此 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調用WebService
我們使用VS創(chuàng)建一個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> /// 通過構造函數(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ù)轉化為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">參數(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; } } }
然后啟動調試,查看輸出結果
調試的時候可以看到返回結果,在看看頁面返回的結果
這樣就完成了WebService的調用。生產(chǎn)環(huán)境中我們可以URL地址寫在配置文件里面,然后程序里面去讀取配置文件內容,這樣就可以實現(xiàn)動態(tài)調用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> /// 通過構造函數(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 // 讀取配置文件里面設置的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ù)轉化為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">參數(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)調用WebService了。
到此這篇關于ASP.NET Core使用HttpClient調用WebService的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Asp.Net中的Action和Func委托實現(xiàn)
這篇文章主要介紹了Asp.Net中的Action和Func委托的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12asp.net實現(xiàn)根據(jù)城市獲取天氣預報的方法
這篇文章主要介紹了asp.net實現(xiàn)根據(jù)城市獲取天氣預報的方法,涉及asp.net調用新浪接口獲取天氣預報信息的實現(xiàn)技巧,非常簡單實用,需要的朋友可以參考下2015-12-12Asp.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