1.在Startup.cs的ConfigureServices方法内添加注入这个HttpClient 这个内置对象
services.AddHttpClient();
readonly IHttpClientFactory _httpClientFactory;
/// <summary>
/// 通过构造函数实现注入
/// </summary>
/// <param name="httpClientFactory"></param>
public TestController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
/// <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;
}
[HttpPost]
public async Task<string> selectcityPost(string byProvinceName)
{
string strResult = "";
try
{
// url地址格式:WebService地址+方法名称
// WebService地址:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
// 方法名称: getSupportCity
string url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity";
// 参数
Dictionary<string, string> dicParam = new Dictionary<string, string>();
//参数名
dicParam.Add("byProvinceName", byProvinceName);
// 将参数转化为HttpContent
HttpContent content = new FormUrlEncodedContent(dicParam);
strResult = await PostHelper(url, content);
}
catch (Exception ex)
{
strResult = ex.Message;
}
return strResult;
}
- 本文标题: NETCoreAPI调用WebService接口
- 文章分类:【.NET/Web】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.