.Net Core third-party call WebService

This example uses a .net core2.2 version, Microsoft offers extended access third-party services, only need to add Startup.cs in.

 It is followed directly by DI. Examples are as follows:

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;
        }
    }
}

Guess you like

Origin www.cnblogs.com/az4215/p/12467308.html