Код: Выделить всё
MyHttpService:
namespace WebApplication1.UComon
{
public class MyHttpService
{
private readonly HttpClient _httpClient;
public MyHttpService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task GetExternalData(string url)
{
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return null;
}
}
}
}
Код: Выделить всё
TestController:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.UComon;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly MyHttpService _httpService;
public TestController(MyHttpService httpService)
{
_httpService = httpService;
}
#region 测试httpclient
[HttpGet, Route("PostHttp")]
public IActionResult PostHttp()
{
string responseBody = "";
//var service = new HttpService();
//string getResponse = service.GetAsync("https://www.baidu.com/").Result;
responseBody = _httpService.GetExternalData("https://www.baidu.com/").Result;
return Ok(responseBody);
}
#endregion
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... after-rece