.Net Core调用第三方WebService

本示例使用的是.net core2.2版本,微软提供了访问第三方服务的扩展,只需要在Startup.cs中添加。

 紧接着就是通过DI直接使用。示例如下:

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace demo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public ValuesController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        [HttpGet]
        public async Task<ActionResult<string>> Get()
        {
            var url = @"http://127.0.0.1:8888/demo/test.asmx/save";

            Dictionary<string, string> dicParam = new Dictionary<string, string>();
            dicParam.Add("id", "1");
            dicParam.Add("name", "张三");
            HttpContent content = new FormUrlEncodedContent(dicParam);

            return await RemoteHelper(url, content);
        }

        private async Task<string> RemoteHelper(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();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return result;
        }
    }
}
posted @ 2020-03-12 09:57  酷学大叔  阅读(1974)  评论(0编辑  收藏  举报