.NET HttpClient

环境搭建

服务注册

builder.Services.AddHttpClient();

创建实体类

csharp 复制代码
namespace HttpClient
{
    public class RequestModel
    {
        public string userName { set; get; }
        public string password { set; get; }

    }

    public class ApiResult
    {
        bool IsSuccess { set; get; }

        object Result { set; get; }

        string Msg { set; get; }
    }
}

创建服务提供类

csharp 复制代码
using Microsoft.AspNetCore.Mvc;

namespace HttpClient.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpPost]
        public object Post([FromBody] RequestModel model)
        {
            return model;

        }
    }
}

测试

ini 复制代码
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using static System.Net.Mime.MediaTypeNames;

namespace HttpClient.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class Demo : ControllerBase
    {

        private readonly IHttpClientFactory _httpClientFactory;

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

        [HttpPost]
        public async Task<string> Post()
        {
            RequestModel req = new RequestModel
            {
                userName = "zhangsan",
                password = "password",
            };
            // 包装参数
            StringContent stringContent = new StringContent(
                JsonSerializer.Serialize(req),
                Encoding.UTF8,
                Application.Json
                );
            System.Net.Http.HttpClient httpClient = _httpClientFactory.CreateClient();
            using var response = await httpClient.PostAsync("https://localhost:7038/WeatherForecast/Post", stringContent);
            var task = response.Content.ReadAsStringAsync();
            return await task;
        }


        [HttpGet]
        public async Task<string> Get()
        {
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7038/WeatherForecast/Get")
            {
                Headers =
                {
                    // 设置请求头
                }
            };

            var client = _httpClientFactory.CreateClient();
            HttpResponseMessage httpResponseMessage = client.Send(httpRequestMessage);
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                var result = await httpResponseMessage.Content.ReadAsStringAsync();
                 return result;
            }
            else
            {
                return "请求失败";
            }
        }
    }
}

调用HttpGet

调用HttpPost

相关推荐
短剑重铸之日2 小时前
《ShardingSphere解读》07 读写分离:如何集成分库分表+数据库主从架构?
java·数据库·后端·架构·shardingsphere·分库分表
wefly20173 小时前
m3u8live.cn 在线M3U8播放器,免安装高效验流排错
前端·后端·python·音视频·前端开发工具
zhanggongzichu4 小时前
小白怎么理解后端分层概念
后端·全栈
stark张宇4 小时前
Golang后端面试复盘:从Swoole到IM架构,如何支撑360w用户的实时消息推送?
后端
小码哥_常5 小时前
从0到1:搭建Spring Boot 3企业级认证授权平台
后端
小码哥_常5 小时前
告别扫库噩梦!Spring Boot+Redis让订单超时管理飞起来
后端
大傻^5 小时前
Spring AI Alibaba 快速入门:基于通义千问的AI应用开发环境搭建
java·人工智能·后端·spring·springai·springaialibaba
IT_陈寒6 小时前
SpringBoot实战:3个隐藏技巧让你的应用性能飙升50%
前端·人工智能·后端
彭于晏Yan6 小时前
MQTT消息服务
spring boot·后端·中间件
程序员Sunday7 小时前
Claude Code 生态爆发:5个必知的新工具
前端·人工智能·后端